gpt4 book ai didi

ruby 在每个循环中获取下一个值

转载 作者:数据小太阳 更新时间:2023-10-29 06:40:59 26 4
gpt4 key购买 nike

我可以在每个循环中获取下一个值吗?

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

答案在哪里..

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

我还可以获得下一个值的下一个吗?

最佳答案

早在Ruby 1.8.7 , Enumerable 模块有一个方法 each_cons这几乎完全符合您的要求:

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]

唯一的问题是它不会重复最后一个元素。但这很容易修复。具体来说,你想要

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

但你也可以这样做:

range = 1..5

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

p result # => 29

或者,您可能会发现以下内容更具可读性:

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

关于ruby 在每个循环中获取下一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7707743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com