在ruby中for循环的语法

如何在Ruby中执行这种for循环?

for(int i=0; i<array.length; i++) { } 
 array.each do |element| element.do_stuff end 

要么

 for element in array do element.do_stuff end 

如果你需要索引,你可以使用这个:

 array.each_with_index do |element,index| element.do_stuff(index) end 
 limit = array.length; for counter in 0..limit --- make some actions --- end 

另一种方式是这样的

 3.times do |n| puts n; end 

这将打印0,1,2,所以可以像数组迭代器一样使用

认为这个变体更适合作者的需求

我继续打这个作为谷歌“rubyfor循环”的顶部链接,所以我想添加一个循环的解决scheme,其中步骤不是简单的'1'。 对于这些情况,您可以使用Numerics和Date对象上存在的“step”方法。 我认为这是一个“for”循环的近似值。

 start = Date.new(2013,06,30) stop = Date.new(2011,06,30) # step back in time over two years, one week at a time start.step(stop, -7).each do |d| puts d end 
 array.each_index do |i| ... end 

这不是Rubyish,但它是从Ruby的问题做循环的最好方法

要循环迭代固定次数,请尝试:

 n.times do #Something to be done n times end 

什么? 从2010年开始,没有人提到Ruby对于/ in循环罚款(这只是没有人使用它):

 ar = [1,2,3,4,5,6] for item in ar puts item end 

如果你不需要访问你的数组 ,(只是一个简单的for循环),你可以使用upto或each:

取决于:

 1.9.3p392 :030 > 2.upto(4) {|i| puts i} 2 3 4 => 2 

每:

 1.9.3p392 :031 > (2..4).each {|i| puts i} 2 3 4 => 2..4 
 ['foo', 'bar', 'baz'].each_with_index {|j, i| puts "#{i} #{j}"} 

等价将是

 for i in (0...array.size) end 

要么

 (0...array.size).each do |i| end 

要么

 i = 0 while i < array.size do array[i] i = i + 1 # where you may freely set i to any value end 

Ruby的枚举循环语法是不同的:

 collection.each do |item| ... end 

这读取为“调用'block'作为参数的数组对象实例'collection'的'each'方法。 Ruby中的块语法是用于单行语句的“do … end”或“{…}”。

块参数“| item |” 是可选的,但如果提供,第一个参数自动表示循环的枚举项目。