Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing enumerable in Ruby

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?

like image 776
Mateusz Chromiński Avatar asked Jun 01 '12 16:06

Mateusz Chromiński


1 Answers

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]
like image 155
tokland Avatar answered Sep 21 '22 13:09

tokland