Jun
14
2011

For Loops in Ruby

There is no C++/Java/PHP type for loop in Ruby like this -
for( init, while-condition, increment ) { // code here }

So i just tried to write one in Ruby for fun, here is the code -

$ irb
irb(main):001:0> def for_(x, cond, inc)
irb(main):002:1>   loop do
irb(main):003:2*     break if !cond.call
irb(main):004:2>     inc.call
irb(main):005:2>     yield
irb(main):006:2>   end
irb(main):007:1> end
=> nil
irb(main):008:0> for_(x = 0, ->{x < 5}, ->{x += 1}) {
irb(main):009:1*   puts 'binarytides'
irb(main):010:1> }
binarytides
binarytides
binarytides
binarytides
binarytides
=> nil

So whats going on ?
1. First of all, the loop method in Ruby accepts a block and loops over it until a break is encountered.
2. ->{x < 5} and ->{x += 1} are basically shorter form of lambda’s. So they are equivalent to lambda {x < 5} and lambda {x += 1}
3. cond.call and inc.call executes the two lambdas respectively. inc.call increments x by 1 everytime the loop method loops, and as soon as it is not less than 5, a break is encountered at “break if !cond.call”
4. yield is used to yield/execute the block that is passed to for_ method and hence prints binarytides.
5. You might be wondering why i did not use for instead of for_, that is because ruby already has a for .. in loop and so for is a reserved word.

This experiment or example was just for fun stuff. You probably wont need it. Instead you could use different methods like -
1. 5.times { puts ‘binarytides’ }
2. 1.upto(5) { puts ‘binarytides’ }
3. while/unless loops

Cheers!

Popularity: 1% [?]

Leave a comment