如何在Ruby中创建整数循环?


71

我认为变量“ x”。我需要显示一些代码“ x”的次数。

我基本上想建立一个像这样的循环:

for i = 1 to x
  do something on (i)
end

有没有办法做到这一点?

Answers:





11

您可以each在1到x的范围内执行一个简单的循环:

(1..x).each do |i|
  #...
end

10

尝试以下简单的Ruby Magics :)

(1..x).each { |n| puts n }
x.times { |n| puts n }
1.upto(x) { |n| print n }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.