jovhenni19 - 8 months ago 27

Ruby Question

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

Like this:

```
range = 1..5
store = 0
range.each_with_index do |value, i|
next_value = range.to_a[i+1].nil? ? 0 : range.to_a[i+1]
store += value + next_value
end
p store # => 29
```

There may be better ways, but this works.

You can get the next of the next value like this:

```
range.to_a[i+2]
```