typestar

select and detect in Ruby

Filtering a collection down to the elements you actually want.

nums = (1..20).to_a

evens = nums.select { |n| n.even? }
puts evens.inspect

odds = nums.reject(&:even?)
puts odds.first(5).inspect

# detect returns the first match, not all of them
first_big = nums.detect { |n| n * n > 50 }
puts first_big

puts nums.partition { |n| n % 3 == 0 }.inspect

How it works

  1. select keeps matching elements; reject drops them.
  2. detect stops at the first match and returns it alone.
  3. partition splits one array into a matching and a failing half.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
288
Tokens
78
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 58 seconds.

Type this snippet

Step 2 of 3 in Blocks & iterators, step 11 of 29 in Language basics.

← Previous Next →