ruby get next value on each loop

jovhenni19 picture jovhenni19 · Oct 10, 2011 · Viewed 11.2k times · Source

Can I get the next value in an each loop?

(1..5).each do |i|
    @store = i + (next value of i)
end

where the answer would be..

1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 = 29

And also can I get the next of the next value?

Answer

Justin picture Justin · Jul 22, 2015

From as early as Ruby 1.8.7, the Enumerable module has had a method each_cons that does almost exactly what you want:

each_cons(n) { ... } → nil
each_cons(n) → an_enumerator

Iterates the given block for each array of consecutive <n> elements. If no block is given, returns an enumerator.

e.g.:

(1..10).each_cons(3) { |a| p a }
# outputs below
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 10]

The only problem is that it doesn't repeat the last element. But that's trivial to fix. Specifically, you want

store = 0
range = 1..5

range.each_cons(2) do |i, next_value_of_i|
    store += i + next_value_of_i
end
store += range.end

p store # => 29

But you could also do this:

range = 1..5

result = range.each_cons(2).reduce(:+).reduce(:+) + range.end

p result # => 29

Alternatively, you may find the following to be more readable:

result = range.end + range.each_cons(2)
                          .reduce(:+)
                          .reduce(:+)