Ruby Array - reverse iterate with next and before element

Siva

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 ?

falsetru

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]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related