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