11

I'm trying to reverse Enumerable (like Array) without using reverse method, but using reverse_each iterator.

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?

Mateusz Chromiński
  • 2,742
  • 4
  • 28
  • 45

3 Answers3

24

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]
tokland
  • 66,169
  • 13
  • 144
  • 170
-1

Another method would be [1, 2, 3].reverse_each.to_a

Dorian
  • 22,759
  • 8
  • 120
  • 116
-1

(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

Neha Chopra
  • 1,761
  • 11
  • 11