使用Ruby,我如何迭代for循环n次

问题描述 投票:34回答:3

我有一个基本的ruby循环

for video in site.posts
  video.some_parameter
endfor

我想运行这个循环2或3次。

这可能吗?

ruby for-loop
3个回答
77
投票
3.times do
   # do work here
end 

检查http://www.tutorialspoint.com/ruby/ruby_loops.htm


9
投票

这是糟糕的风格。

3.times do
  site.posts.each do |video|
    video.some_parameter
  end
end

或者如果video.some_parameter是一行,

3.times do
  site.posts.each { |video| video.some_parameter }
end

见:https://github.com/bbatsov/ruby-style-guide#source-code-layout


1
投票

如果你需要一个索引:

5.times do |i|
  print i, " "
end

返回:

0 1 2 3 4

参考:https://apidock.com/ruby/Integer/times

© www.soinside.com 2019 - 2024. All rights reserved.