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
selectkeeps matching elements;rejectdrops them.detectstops at the first match and returns it alone.partitionsplits one array into a matching and a failing half.
Keywords and builtins used here
puts
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.
Step 2 of 3 in Blocks & iterators, step 11 of 29 in Language basics.