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

时间:2022-10-19 14:29:50

I have a basic ruby loop

我有一个基本的ruby循环

for video in site.posts
  video.some_parameter
endfor

I want to run this loop 2 or 3 times.

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

Is this possible?

这可能吗?

2 个解决方案

#1


64  

3.times do
   # do work here
end 

check http://www.tutorialspoint.com/ruby/ruby_loops.htm

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

#2


7  

It's bad style to use for.

这是糟糕的风格。

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

or if video.some_parameter is one line,

或者如果video.some_parameter是一行,

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

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

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

#1


64  

3.times do
   # do work here
end 

check http://www.tutorialspoint.com/ruby/ruby_loops.htm

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

#2


7  

It's bad style to use for.

这是糟糕的风格。

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

or if video.some_parameter is one line,

或者如果video.some_parameter是一行,

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

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

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