在Ruby中实现循环的最智能,最有效的方法

mab*_*sif 1 ruby

我想知道是否有任何优雅的方法来实现以下方法的循环.我只能提出一个常规while循环(Java程序员)作为以下伪代码:

while x<10       
  search = Google::Search::Web.new()
  search.query = "china"
  search.start = x
end
Run Code Online (Sandbox Code Playgroud)

有人知道更好的方法吗?

Phr*_*ogz 9

许多选择:

# Will go 0..9
10.times do |i|
  search = Google::Search::Web.new()
  search.query = "china"
  search.start = i
end

# Will go 1..10
1.upto(10) do |i|
  search = Google::Search::Web.new()
  search.query = "china"
  search.start = i
end

# Will go 1..10
(1..10).each do |i|
  search = Google::Search::Web.new()
  search.query = "china"
  search.start = i
end
Run Code Online (Sandbox Code Playgroud)

  • 甚至更多的替代品http://alicebobandmallory.com/articles/2010/06/21/a-simple-loop (2认同)