0

Examining the following code

[1,2,3,4].map # => #<Enumerator: [1, 2, 3, 4]:map> 
[1,2,3,4].each # => #<Enumerator: [1, 2, 3, 4]:each> 

we can see that both are an enumerator. One is map and other is each. The method to_enum also returns an enumerator each. Is there any difference between these two enumerators?

sawa
  • 165,429
  • 45
  • 277
  • 381
fotanus
  • 19,618
  • 13
  • 77
  • 111

1 Answers1

2

Yes, when you iterate over the map enumerator, it will take the result and populate it into a new array:

[1,2,3,4].map.each { |n| n * 2 }  # => [2, 4, 6, 8]

When you iterate over the each enumerator, it will return the original array

[1,2,3,4].each.each { |n| n * 2 }  # => [1, 2, 3, 4]

Map exists to take an array of one type and convert it to an array of a different type, each exists to simply iterate over the array (doing something with a side effect for each element, such as printing it out).

Joshua Cheek
  • 30,436
  • 16
  • 74
  • 83