Siva
Siva

Reputation: 8058

Ruby Array - reverse iterate with next and before element

How to reverse iterate an Array with next and before element of the current element ?

Is it possible to use each_cons with reverse_each ?

Upvotes: 4

Views: 516

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110755

This might work for you:

class Array
  alias :old_each :each
  def each
    reverse.old_each {|e| yield e}
  end
end

a = [1,2,3]
a.each {|e| print "#{e} "}  # => 3 2 1 

Note you have to be careful with this because Array, for efficiency reasons, overloads some Enumerable methods without using each.

I used this in a big project with my previous employer, adding it right before I left. Boy, was I glad to get out of there.

Edit: It just occurred to me that I could have improved this in the above-referenced project:

  def each
    if rand(1000) == 500
      reverse.old_each {|e| yield e}
    else
      old_each {|e| yield e}
    end
  end

Upvotes: 2

falsetru
falsetru

Reputation: 369494

Yes, it is possible.

[1,2,3,4,5,6].reverse_each.each_cons(3) { |before, current, next_|
  p [before, current, next_]
}

prints

[6, 5, 4]
[5, 4, 3]
[4, 3, 2]
[3, 2, 1]

([nil]+[1,2,3,4,5,6]+[nil]).reverse_each.each_cons(3) { |before, current, next_|
  p [before, current, next_]
}

prints

[nil, 6, 5]
[6, 5, 4]
[5, 4, 3]
[4, 3, 2]
[3, 2, 1]
[2, 1, nil]

Upvotes: 10

Related Questions