ruby 在每个循环中获取下一个值
我可以在每个循环中获取下一个值吗?
(1..5).each do |i|
@store = i + (next value of i)
end
答案是..
1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 = 29
我还能得到下一个值吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
早于 Ruby 1.8.7,Enumerable 模块有一个方法
each_cons
< /a> 这几乎完全符合你的要求:唯一的问题是它不重复最后一个元素。但这是微不足道的修复。具体来说,您想要
但您也可以这样做:
或者,您可能会发现以下内容更具可读性:
From as early as Ruby 1.8.7, the Enumerable module has had a method
each_cons
that does almost exactly what you want:The only problem is that it doesn't repeat the last element. But that's trivial to fix. Specifically, you want
But you could also do this:
Alternatively, you may find the following to be more readable:
像这样:
可能有更好的方法,但这是有效的。
您可以像这样获取下一个值的下一个:
Like this:
There may be better ways, but this works.
You can get the next of the next value like this:
一种不使用索引的方法是 Enumerable#zip:
One approach that wouldn't use indexes is Enumerable#zip: