top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the purpose of yield in Ruby ?

+2 votes
499 views
What is the purpose of yield in Ruby ?
posted May 6, 2014 by Balwinder

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Ruby provides a yield statement that eases the creation of iterators.

The first thing I noticed was that its behavior is different from the C# yield statement (which I knew from before).

Ruby's yield statement gives control to a user specified block from the method's body. A classic example is the Fibonacci Sequence:

class NumericSequences
   def fibo(limit)
     i = 1
     yield 1 
     yield 1 
     a = 1
     b = 1
     while (i < limit)
         t = a
         a = a + b
         b = t
         yield a
         i = i+1
     end
  end 
      ...

end

The fibo method can be used by specifying a block that will be executed each time the control reaches a yield statement. For example:

irb(main):001:0> g = NumericSequences::new
=> #<NumericSequences:0xb7cd703c>
irb(main):002:0> g.fibo(10) {|x| print "Fibonacci number: #{x}\n"}
Fibonacci number: 1
Fibonacci number: 1
Fibonacci number: 2
Fibonacci number: 3
Fibonacci number: 5
Fibonacci number: 8
Fibonacci number: 13
Fibonacci number: 21
Fibonacci number: 34
Fibonacci number: 55
Fibonacci number: 89
answer May 7, 2014 by Anil Chaurasiya
...