1

If you want a method that collects an array without modifying it, you can use map, and you'll have something that works the same as each. For example, you could do this:

array.each do |x|
  x += 10
  print "#{x}"
end

but you could just as easily do this:

array.map{|x| print (x + 10).to_s}

and it would have the exact same result. While each can only do that, map can alter its function using the !, so I don't see why I would use each anymore. Could you explain why I should ever use each instead of map if map seems more versatile?

sawa
  • 165,429
  • 45
  • 277
  • 381
  • `map` is a functional programming idiom in which you "map" a function or in Ruby's case a block over an object and return a new object. – squiguy May 29 '14 at 05:11

1 Answers1

1

No. Use each for side-effects; use map for a (side-effect free) transformation.

While they both iterate the enumerable (at some point1), map collects the transformed results which should be used. To say map is a more powerful each is like saying a method that returns an unused value is more powerful than a method does not return a value - it's not of being more powerful, it's about using the correct tool.

Thus, while map can "do" what each does (by evaluation of supplied block), it does more and is useful for a different task: when the transformation, and not the side-effect, is desired. It is often considered poor practice to perform side-effects in a map (excluding, perhaps, the mutation of the mapped objects).

1Furthermore, map and each are not strictly interchangeable. In lazy vs. eager situations, a transformation like map can be lazy while each is only useful for side-effects and is never lazy. (It is not possible for each to be lazy because there is no resulting sequence to "observe" and force the evaluation later.)

user2864740
  • 60,010
  • 15
  • 145
  • 220