Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 452
thesecretmaster Avatar asked Feb 21 '26 19:02

thesecretmaster


1 Answers

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
like image 138
sawa Avatar answered Feb 24 '26 16:02

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!