This is described in the Ruby documentation in several places, but the easiest to understand for your use in the Array documentation for each :
each { |item| block } β ary each β Enumerator
Calls this block once for each element in self, passing this element as a parameter. Returns an array.
If the block is not specified, the counter is returned.
a = [ "a", "b", "c" ] a.each {|x| print x, " -- " }
gives:
a -- b -- c --
Notice that it says: "Returns the array itself."
Compare this to map :
map { |item| block } β new_ary map β Enumerator
Invokes this block once for each self element.
Creates a new array containing the values ββreturned by the block.
See also List # collect.
If no blocks are specified, a counter is returned instead.
a = [ "a", "b", "c", "d" ] a.collect { |x| x + "!" } #=> ["a!", "b!", "c!", "d!"] a.map.with_index { |x, i| x * i } #=> ["", "b", "cc", "ddd"] a #=> ["a", "b", "c", "d"]
Notice that it says: "Creates a new array containing the values ββreturned by the block."
This example should help to find out above:
foo = [1,2,3] foo.each { |i| puts i + 1 }
where # => is the return value of the block, and # >> is the captured STDOUT from puts .
And knowing all this, use each when you want to display elements in an array or retrieve and reuse these elements as parameters or build things. Use map when you want to change the elements of an array to something else.