4

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 ?

2 Answers 2

10

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]
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

I had a word with @Arup. He's now familiar with the term, 'code-bomb'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.