typestar

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

  1. each visits every element; the block does the work.
  2. map builds a new array from each block result.
  3. map(&:upcase) is the shorthand when the block just calls a method.
  4. each_with_index pairs elements with their positions.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Blocks & iterators, step 10 of 29 in Language basics.

← Previous Next →