Tuesday, October 11, 2011

Ruby Loops

 As for looping mechanisms, Ruby has a rich set. The while and until control structures are both pretest loops, and both work as expected: One specifies a continuation condition for the loop, and the other specifies a termination condition. They also occur in "modifier" form such as if and unless. There is also the loop method of the Kernel module (by default an infinite loop), and there are iterators associated with various classes.

# Loop 1 (while)
i=0
while i < list.size do
print "#{list[i]} "
i += 1
end

# Loop 2 (until)
i=0
until i == list.size do
print "#{list[i]} "
i += 1
end

# Loop 3 (for)
for x in list do
print "#{x} "
end

# Loop 4 ('each' iterator)
list.each do |x|
print "#{x} "
end

# Loop 5 ('loop' method)
i=0
n=list.size-1
loop do
print "#{list[i]} "
i += 1
break if i > n
end

# Loop 6 ('loop' method)
i=0
n=list.size-1
loop do
print "#{list[i]} "
i += 1
break unless i <= n
end

# Loop 7 ('times' iterator)
n=list.size
n.times do |i|
print "#{list[i]} "
end

# Loop 8 ('upto' iterator)
n=list.size-1
0.upto(n) do |i|
print "#{list[i]} "
end

# Loop 9 (for)
n=list.size-1
for
i in 0..n do
print "#{list[i]} "
end

# Loop 10 ('each_index')
list.each_index do |xt
print "#{list[x]} "
end

No comments:

Post a Comment