Use of yield and return in Ruby

Hoa Nguyen picture Hoa Nguyen · May 4, 2012 · Viewed 16k times · Source

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

Deleteman picture Deleteman · May 4, 2012

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"
end

That's actually the same as doing something like:

def method
  return "hey there"
end

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..."
  yield
end

And then use it like this:

method do
   puts "doing something"
end

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.