Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smartest and most efficient way to implement a loop in Ruby

Tags:

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 = Google::Search::Web.new()
  search.query = "china"
  search.start = x
end

Someone knows a better way?

like image 978
mabounassif Avatar asked Jan 26 '26 02:01

mabounassif


2 Answers

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
like image 78
Phrogz Avatar answered Jan 28 '26 15:01

Phrogz


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

like image 25
Ben Lee Avatar answered Jan 28 '26 14:01

Ben Lee