Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Array - reverse iterate with next and before element

Tags:

arrays

ruby

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 ?

like image 562
Siva Avatar asked Dec 16 '22 05:12

Siva


2 Answers

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]
like image 86
falsetru Avatar answered Jan 10 '23 06:01

falsetru


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
like image 28
Cary Swoveland Avatar answered Jan 10 '23 04:01

Cary Swoveland