Reversing enumerable in Ruby
From 1.8.7, Enumerable#each_*
methods return an enumerator when no block is provided, so those originally imperative methods can now be used in pure expressions.
So, if you want to collect items, use Enumerable#map
on that enumerator:
reversed_values = [1, 2, 3].reverse_each.map { |x| 2*x }#=> [6, 4, 2]
(1..3).reverse_each {|v| p v }
produces:
1 2 3
It Builds a temporary array and traverses that array in reverse order, but do not return the reverse copy of the transformed collection
If no block is given, an enumerator is returned instead.
But map method of ruby
Returns a new array with the results of running block once for every element in enum.
p [1,2,3].reverse_each.map {|v| v }
reverse_each - will act as an iterator
map - will form a new set of collection