thesecretmaster
thesecretmaster

Reputation: 1984

How to define_method with a do and end

I am writing a program that utilizes define_method, but I don't understand how I could define a method like this one:

def mymethod(variable) do
    puts variable
    puts yield
end

Which can be called by:

mymethod("hi") do
    # this is yield
end

Upvotes: 3

Views: 50

Answers (2)

sawa
sawa

Reputation: 168081

You cannot use yield. You need to receive it as a proc object.

define_method(:mymethod) do |variable, &block|
  puts variable
  puts block.call
end

mymethod("foo"){"bar"}
# foo
# bar

mymethod("foo") do "bar" end
# foo
# bar

Upvotes: 3

Aetherus
Aetherus

Reputation: 8888

define_method :my_method do |str, &block|
  # Do something here
  yield  # or block.call
  # Do something here
end

Upvotes: -2

Related Questions