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

TJ *_*ill 39 ruby for-loop

我有一个基本的ruby循环

for video in site.posts
  video.some_parameter
endfor
Run Code Online (Sandbox Code Playgroud)

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

这可能吗?

Hit*_*eeb 85

3.times do
   # do work here
end 
Run Code Online (Sandbox Code Playgroud)

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

  • 如果需要,如何检索索引? (4认同)

Pla*_*rob 9

这是不好的风格来使用的.

3.times do
  site.posts.each do |video|
    video.some_parameter
  end
end
Run Code Online (Sandbox Code Playgroud)

或者如果video.some_parameter是一行,

3.times do
  site.posts.each { |video| video.some_parameter }
end
Run Code Online (Sandbox Code Playgroud)

请参阅:https://github.com/bbatsov/ruby-style-guide#source-code-layout


ric*_*cks 5

If you need an index:

5.times do |i|
  print i, " "
end
Run Code Online (Sandbox Code Playgroud)

Returns:

0 1 2 3 4

Reference: https://apidock.com/ruby/Integer/times