Ruby: each, each_index, map, collect

1. map

map creates a new array containing the values returned by the block.

a = [ “a”, “b”, “c”, “d” ]

print a.map { |x| x + “!” }   #=> [“a!”, “b!”, “c!”, “d!”]

print a                       #=> [“a”, “b”, “c”, “d”]

http://ruby-doc.org/core-2.0/Array.html#method-i-map

2. map! 

map! replaces the element with the value returned by the block.

a = [ “a”, “b”, “c”, “d” ]

print a.map! { |x| x + “!” }   #=> [“a!”, “b!”, “c!”, “d!”]

print a                       #=> [“a!”, “b!”, “c!”, “d!”]

http://ruby-doc.org/core-2.0/Array.html#method-i-map-21

3. each 

each passes in each element to the block. It enumerates over each element but does not change elements or the array. Only local values of each element are changed.

a = [ “a”, “b”, “c”, “d” ]

print a.each { |x| x + “!” }   #=> [“a”, “b”, “c”, “d”]

print a                       #=> [“a”, “b”, “c”, “d”]

http://ruby-doc.org/core-2.0/Array.html#method-i-each

4. each_index

each_index is the same as each but passes the index of the element rather than the element itself

a = [ “a”, “b”, “c”, “d” ]

print a.each_index { |x| a[x] = a[x] + “!” }   #=> [“a!”, “b!”, “c!”, “d!”] 

print a                       #=> [“a!”, “b!”, “c!”, “d!”] 

http://ruby-doc.org/core-2.0/Array.html#method-i-each_index

BUT be aware that is not good practice. For one, people don’t expect each or each_index to mutate the array – use map! instead.

 

And secondly, the ‘+’ is basically creating a new string which you’re then throwing away – a[x] + ‘!’ is better written as a[x].+(‘!) where + is a method that takes a string and returns a string. Better would be a[x] << ‘!’ (but be aware that this mutates the string in the caller’s scope).

See:

http://ruby-doc.org/core-2.0/String.html#method-i-3C-3C

5. collect and collect!

are equivalent to map and map!

More on that here:

http://stackoverflow.com/questions/5254732/ruby-difference-between-map-and-collect

Leave a Reply

Your email address will not be published. Required fields are marked *