Wednesday, May 21, 2008

Loops in Ruby (Looping...For)

There are several ways to write Loops in Ruby:

1. For Loop

#print Hello World three times
For i in 1..3 do
puts "Hello World"
end

2. While / Until Loop

#print Hello World three times
i=0
while i < 3 do
puts "Hello World"
i = i + 1
end

#print Hello World three times
i=1
until i == 3 do
puts "Hello World"
i = i + 1
end

3. upto, downto and times

Every integer is an object in Ruby, and it has methods upto, downto and times.

#print Hello World three times
1.upto(3) do
puts "Hello World"
end

#print Hello World three times
3.downto(1) do
puts "Hello World"
end

#print Hello World three times
3.times do
puts "Hello World"
end

No comments: