0

Good day. I've tried writing this code in ruby

x = [1, 2, 3, 4, 5]
x.each do |a|
    a + 1
end

When I type this in irb, I don't understand why does it return => [1, 2, 3, 4, 5]

I thought it would return => [2, 3, 4, 5, 6] # because of a + 1

  • 2
    Difference between `each`, `map`, `map!` https://stackoverflow.com/a/9429114/16236820 – zswqa Jul 24 '21 at 10:28

1 Answers1

2

each yields the array's elements to the given block (one after another) without modifying the array. At the end, it returns the array, as mentioned in the docs:

[...] passes each successive array element to the block; returns self

You are probably looking for map, which works similar to each but instead of returning self, it ...

[...] returns a new Array whose elements are the return values from the block

Example:

x = [1, 2, 3, 4, 5]
x.map { |a| a + 1 }
#=> [2, 3, 4, 5, 6]

Note that it returns a new array without actually modifying x. There's also map! (with !) which does modify the receiver.

Stefan
  • 109,145
  • 14
  • 143
  • 218