nxhoaf nxhoaf - 1 year ago 96
Ruby Question

Use of yield and return in Ruby

Can anyone help me to figure out the the use of yield and return in Ruby. I'm a Ruby beginner, so simple examples are highly appreciated.

Thank you in advance!

Answer Source

The return statement works the same way that it works on other similar programming languages, it just returns from the method it is used on. You can skip the call to return, since all methods in ruby always return the last statement. So you might find method like this:

def method
  "hey there"

That's actually the same as doing something like:

def method
  return "hey there"

The yield on the other hand, excecutes the block given as a parameter to the method. So you can have a method like this:

def method 
  puts "do somthing..."

And then use it like this:

method do
   puts "doing something"

The result of that, would be printing on screen the following 2 lines:

"do somthing..."
"doing something"

Hope that clears it up a bit. For more info on blocks, you can check out this link.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download