如何在 ruby 中编写负循环,例如 for(i=index; i >= 0; i --)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8926477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write negative loop in ruby like for(i=index; i >= 0; i --)
提问by Manish Shrivastava
How can I write a loop in Ruby that counts down, similar to the following C-style forloop?
如何在 Ruby 中编写一个倒计时循环,类似于以下 C 样式for循环?
for (i = 25; i >= 0; i--) {
print i;
}
回答by gsoni
There are many ways to perform a decrementing loop in Ruby:
在 Ruby 中有很多方法可以执行递减循环:
First way:
第一种方式:
for i in (10).downto(0)
puts i
end
Second way:
第二种方式:
(10).downto(0) do |i|
puts i
end
Third way:
第三种方式:
i=10;
until i<0
puts i
i-=1
end
回答by Mark Thomas
One way:
单程:
25.downto(0) do |i|
puts i
end
回答by steenslag
downtois fine, but there is also the more generic step.
downto很好,但也有更通用的step.
25.step(0, -1){|i| puts i}
回答by Bozhidar Batsov
Try this:
尝试这个:
25.downto(0) { |i| puts i }
回答by seph
Just in case you are working with a range already:
以防万一您已经在使用一个范围:
rng = 0..6
rng.reverse_each { |i| p i }
EDIT - more succinctly:
编辑 - 更简洁:
puts(rng.to_a.reverse)
回答by edgerunner
Here's a simpler one:
这是一个更简单的:
(0..25).reverse_each { |i| print i }

