嵌套产量如何工作?

时间:2013-11-30 19:17:38

标签: ruby yield

我想写一个满足的代码:

SomeClass.new.execute(method) == 3

我有:

class SomeClass
  def execute(method)
    def method
     yield
    end
  end
end

method = 1+2

给了我nil。我对收益率仍然非常困惑。非常感谢任何帮助。

3 个答案:

答案 0 :(得分:5)

您沿着正确的方向行,但您的参数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

答案 1 :(得分:4)

你是一个正确的方向 - 是的。 yield将执行传入的块。所以你想做这样的事情:

class SomeClass
  def execute
    yield
  end
end

然后你可以这样称呼它:

SomeClass.new.execute { 1+2 }

答案 2 :(得分:4)

yield关键字将控制权传递给传递给该方法的任何。你没有通过任何街区,所以无事可做。

你想要这样的东西:

class C
  def execute
    yield    # Pass control to a block that was passed in.
             # Method returns whatever the value of evaluating `b` was.
  end
end

现在你可以做到:

C.new.execute { 1 + 2 }     # Pass block containing a statement "1 + 2".
# => 3                      # The result of evaluating "1 + 2" is
                            #   returned from the #execute method.

如果要传递与要传递的块相对应的方法对象,而不是匿名指定它,可以创建 lambda

b = lambda { 1 + 2 }
C.new.execute &b            # Pass an object to #execute that will be used as
# => 3                      #   the block.

Ruby有一些大致相同的制作lambdas的方法:

lambda { 1 + 2 }
Proc.new { 1 + 2 }
-> { 1 + 2 }
相关问题