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
?
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With