32

How can i iterate over a ruby array and always get two values, the current and the next, like:

[1,2,3,4,5,6].pairwise do |a,b|
  # a=1, b=2 in first iteration
  # a=2, b=3 in second iteration
  # a=3, b=4 in third iteration
  # ...
  # a=5, b=6 in last iteration
end

My usecase: I want to test if an array is sorted, and by having an iterator like this i could always compare two values.

I am not searching for each_slice like in this question: Converting ruby array to array of consecutive pairs

Community
  • 1
  • 1
Andi
  • 1,172
  • 1
  • 11
  • 16

1 Answers1

50

You are looking for each_cons:

(1..6).each_cons(2) { |a, b| p a: a, b: b }
# {:a=>1, :b=>2}
# {:a=>2, :b=>3}
# {:a=>3, :b=>4}
# {:a=>4, :b=>5}
# {:a=>5, :b=>6}
Stefan
  • 109,145
  • 14
  • 143
  • 218
Ursus
  • 29,643
  • 3
  • 33
  • 50
  • 2
    Yes, this is exactly what i need! I looked through [Enumerable](http://ruby-doc.org/core-2.1.0/Enumerable.html) and [Enumerator](http://ruby-doc.org/core-2.1.0/Enumerator.html) but did not see this one. Thx – Andi Jun 22 '16 at 12:14
  • 2
    @Andi and regarding your use case: `ary.each_cons(2).all? { |a, b| a <= b }` returns `true` if the values are sorted. (unfortunately, you can't use `all?(&:<=)` here due to the way `each_cons` yields values) – Stefan Jun 22 '16 at 12:44