如何使用 do 和 end 定义 define_method

3

我正在编写一个程序,使用define_method,但我不知道如何定义这样的方法:

def mymethod(variable) do
    puts variable
    puts yield
end

可以通过以下方式进行调用:

mymethod("hi") do
    # this is yield
end
2个回答

3

你不能使用 yield,而需要将其接收为 proc 对象。

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

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

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

@thesecretmaster 因为 yield 将被解释为词法作用域。 - sawa
此外,该方法不能像 my_method("foo") do; "bar"; end 这样被调用。 - thesecretmaster
哦...我刚意识到,测试时打错了一个字...糟糕抱歉。非常好的答案! - thesecretmaster

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接