Thursday, April 17, 2008

Ruby: Lopping through


Share at Facebook

Once again Ruby guys. But this time with Looping of Ruby on various way. Most of the cases we are very much used to on While/For/Foreach etc looping system. I'm discussing the all possible looping system of Ruby that I know so far. Just use the way you need. All are designed to use for specific purpose and benifit.

1) This is the traditional while loop like other languages. First declare the i for loop, then put at condition.
i = 1;
while(i <= 5)
print "Loop ",i,"\n";
i = i + 1;
end;
2) This is new to me. I didn't find this kinds of things on any other languages. But I like this loop compare to others. Its easy.
1.upto(5){|i|
print "Loop ",i,"\n";
}
3)Another example, This one is easy but looks complicated to me in terms of syntex.
5.times do |i|
print "Loop ",i,"\n";
end
4) An easy foor loop like Perl Python.
for i in (1..5)
print "Loop ",i,"\n";
end
5) Another variation, but I found this one even complicated. I rather like for() instead of this.
(1..5).each do |i|
print "Loop ",i,"\n";
end
Hope this time it was enough to expand looping on Ruby.




2 comments:

Anonymous said...

please add me to msn: empapa@gmail.com

Wayne Conrad said...

The semicolons are syntactic sugar when only one statement is on a line. You only need them if you want to look like C.