each and map in Ruby
The two iterators that start every Ruby program.
words = %w[typing at the speed of thought]
words.each { |w| puts w }
lengths = words.map { |w| w.length }
puts lengths.inspect
# &:sym is the shorthand when the block only calls one method
puts words.map(&:upcase).inspect
puts words.each_with_index.map { |w, i| "#{i}: #{w}" }.inspect
How it works
eachvisits every element; the block does the work.mapbuilds a new array from each block result.map(&:upcase)is the shorthand when the block just calls a method.each_with_indexpairs elements with their positions.
Keywords and builtins used here
puts
The run, in numbers
- Lines
- 11
- Characters to type
- 288
- Tokens
- 67
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 47 seconds.
Step 1 of 3 in Blocks & iterators, step 10 of 29 in Language basics.