A simple loop

Posted by Jonas Elfström Mon, 21 Jun 2010 19:56:00 GMT

There's more than one way to skin a cat and the same is true for looping in Ruby. This is a silly post with a silly number of ways to

print the integers from 1 to 10.

If you're a BASIC-programmer and are getting your feet wet with Ruby, you might end up with something like this.

1
2
3
4
while i<=10 do
   puts i
   i+=1
end


That and the following for-loop is not the usual Ruby way of looping.

1
2
3
for i in 1..10
 puts i
end


Instead rubyists often iterates over ranges or arrays with each.

(1..10).each {|i| puts i }


But for simple integer loops like this, we also have upto

1.upto(10) {|i| puts i }


and times.

10.times {|i| puts i+1}


Here's where I should've stopped but I can't help myself, I just have to show off with some Symbol#to_proc "magic".

(0..10).inject(&:p)


The above works because p is an alias of puts and & converts the symbol :p to a proc that is called with the numbers in the range as parameters.

The alias p also gives us, what I think has to be, the shortest possible way.

p *1..10


You could argue that it's a bad thing that there are so many ways to do something as simple as this. But I see no big problem here, if any at all, even though these are hardly all possible ways to loop over integers in Ruby.

Posted in Ruby | no comments

Comments

Comments are closed