top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

What is the purpose of yield in Ruby ?

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

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social 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
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...