3

Why does the long version of passing a block to Array#map (#2 below) return an enumerator, while #1 and #3 below return arrays?

Method #1: Returns an array

result = [1, 2, 3].map do |num|
  num * 2
end
p result

Method #2: Returns an enumerator

p [1, 2, 3].map do |num|
  num * 2
end

Method #3: Returns an array

p [1, 2, 3].map {|num| num * 2}
Tomero
  • 183
  • 2
  • 10

1 Answers1

2

In #2, you are passing the return value of map, which is an enumerator, into p.

[1, 2, 3].map #returns an enumerator

In #1 and #3, on the other hand, you are passing the block directly into map, so the return value is an array.

p ([1, 2, 3].map do |num|
  num * 2
end) # returns an array

If you enclose the whole thing in brackets, it will give you the proper return value.

Sekalf Nroc
  • 457
  • 3
  • 7