使用 Ruby,我如何迭代 for 循环 n.times
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13036371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Ruby, how can I iterate over a for loop n.times
提问by TJ Sherrill
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?
这可能吗?
回答by Hitham S. AlQadheeb
3.times do
# do work here
end
回答by Plasmarob
It's bad style to use for.
使用for的风格很糟糕。
3.times do
site.posts.each do |video|
video.some_parameter
end
end
or if video.some_parameteris 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
回答by ricks
If you need an index:
如果您需要索引:
5.times do |i|
print i, " "
end
Returns:
返回:
0 1 2 3 4
0 1 2 3 4
Reference: https://apidock.com/ruby/Integer/times

