我想写一个满足的代码:
SomeClass.new.execute(method) == 3
我有:
class SomeClass def execute(method) def method yield end end end method = 1+2
这给了我nil
.我对收益率仍然非常困惑.任何帮助是极大的赞赏.
您沿着正确的方向行,但您的参数method
必须是代码块.
您可以通过几种不同的方式创建代码块.最常见的是匿名,使用{...}
或do...end
.如果要将代码块存储在需要调用的变量中,SomeClass.new.execute(method)
可以使用Proc.new
.
还有其他创建块的方法(使用lambda
语法),但它们超出了这个问题的范围.
这将使用存储在变量中的块:
class SomeClass def execute yield end end method = Proc.new { 1+2 } SomeClass.new.execute(&method) # => 3
或者,更简洁,
SomeClass.new.execute { 1 + 2 } # => 3