How does a nested yield work?

ruby, yield

Solution

You're along the right lines, but your parameter `method` must be a code block.

You can create a code block in a few different ways. The most common is anonymously, using `{...}` or `do...end`. If you want to store the code block in a variable, which you'd need to do to call `SomeClass.new.execute(method)`, you can use `Proc.new`.

There are other ways of creating blocks (using the `lambda` syntax), but they are beyond the scope of this question.

This will work using a block stored in a variable:

class SomeClass
  def execute
    yield
  end
end

method = Proc.new { 1+2 }
SomeClass.new.execute(&method) # => 3

Or, more succinctly,

SomeClass.new.execute { 1 + 2 } # => 3

Problem

I want to write a code that satisfies: ``` SomeClass.new.execute(method) == 3 ``` and I have: ``` class SomeClass def execute(method) def method yield end end end method = 1+2 ``` which gives me `nil`. I'm still very confused about yield. Any help is greatly appreciated.

Original source