Mateusz Chromiński Mateusz Chromiński - 6 months ago 6x
Ruby Question

Reversing enumerable in Ruby

I'm trying to reverse Enumerable (like Array) without using

method, but using

I hoped, that following code is enough:

p [1,2,3].reverse_each {|v| v }

however the block doesn't return array in reversed orded. Of course I could write

[1,2,3].reverse_each {|v| p v }

but I'd like to collect items in the first way. What is the source if this behaviour and how should I write my expression to fulfill requirement?


From 1.8.7, Enumerable#each_* methods return an enumerator when no block is provided. That's quite nice: a lot of originally imperative methods can now be used in functional fashion as expressions.

So, if you want to collect items, call map on said enumerator:

>> [1, 2, 3] { |x| 2*x }
=> [6, 4, 2]