Smartest and most efficient way to implement a loop in Ruby
I would like to know if there is any elegant way to implement a loop for the following method. I can only come up with a regular while loop (Java programmer) as the following pseudo code:
while x<10
search 开发者_StackOverflow中文版= Google::Search::Web.new()
search.query = "china"
search.start = x
end
Someone knows a better way?
Many alternatives:
# 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
Do you mean to do something like this?
(1..9).each do |i|
search = Google::Search::Web.new()
search.query = "china"
search.start = i
end
That will run the query with start at 1
, then start at 2
, all the way up to start at 9
. The 1..9
syntax is a range, inclusive on both sides.
UPDATE: The (1..9).each
is probably the most idiomatic way to do this in ruby, but Jonas Elfström posted a cool link that quickly demonstrates some alternatives:
http://alicebobandmallory.com/articles/2010/06/21/a-simple-loop
10.times do |i|
search = Google::Search::Web.new()
search.query = "china"
search.start = x
loop
Integers have the times
method that takes a block and loops n times where n is the number.
Since it doesn't look like the value of x
never actually changes, there are two possible ways to rewrite this. Either x >= 10
before the loop starts, then it will never be run, and it can simply be replaced with nothing. Otherwise, it's an infinite loop, and the most idiomatic way to write that is
loop do
search = Google::Search::Web.new
search.query = 'china'
search.start = x
end
If you don't know the value of x
beforehand, you can simply make the loop conditional:
loop do
search = Google::Search::Web.new
search.query = 'china'
search.start = x
end if x < 10
If x
is a message send whose method changes its return value, then I don't see any obvious way to improve your code other than removing the superfluous braces.
精彩评论