ruby中&block是可选的吗?

时间:2022-02-05 11:13:18

Is this possible? For example if I have:

这是可能的吗?例如,如果我有:

module Sample
  def self.method_name(var, &block)
    if var == 6
      call_other_method(var, &block)
    else
      call_other_method(var)
    end
  end

  def self.call_other_method(var, &block)
    # do something with var and block, assuming block is passed to us.
  end
end

So in the above example, if you call the Sample.method_name and pas it a 3 and a block, that block would not be used because the input doesn't match the conditional. But is this possible? Can you make a &block optional?

在上面的例子中,如果你调用样本。method_name并将它作为一个3和一个块,这个块将不会被使用,因为输入与条件不匹配。但这是可能的吗?你可以选择一个&block吗?

I made the assumption, based on other stack questions that you can pass a &block from one method to the next as shown above, if this is wrong please fill me in.

我做了一个假设,基于其他堆栈问题,您可以将&block从一个方法传递到另一个方法,如上面所示,如果这是错误的,请告诉我。

2 个解决方案

#1


6  

Sure. Check out block_given? in the ruby docs.

确定。看看block_given吗?在ruby文档。

http://ruby-doc.org/core-2.2.1/Kernel.html#method-i-block_given-3F

http://ruby-doc.org/core-2.2.1/Kernel.html method-i-block_given-3F

module Sample
  def self.method_name(var, &block)
    if var == 6
      call_other_method(var, &block)
    else
      call_other_method(var)
    end
  end

  def self.call_other_method(var, &block)
    puts "calling other method with var = #{var}"
    block.call if block_given?
    puts "finished other method with var = #{var}"
  end
end

When run the output is:

运行时输出为:

calling other method with var = 6
this is my block
finished other method with var = 6
calling other method with var = 3
finished other method with var = 3

#2


2  

Yes, it is possible. In fact, the code you posted already works just fine as-is.

是的,这是可能的。事实上,您发布的代码已经可以正常工作了。

#1


6  

Sure. Check out block_given? in the ruby docs.

确定。看看block_given吗?在ruby文档。

http://ruby-doc.org/core-2.2.1/Kernel.html#method-i-block_given-3F

http://ruby-doc.org/core-2.2.1/Kernel.html method-i-block_given-3F

module Sample
  def self.method_name(var, &block)
    if var == 6
      call_other_method(var, &block)
    else
      call_other_method(var)
    end
  end

  def self.call_other_method(var, &block)
    puts "calling other method with var = #{var}"
    block.call if block_given?
    puts "finished other method with var = #{var}"
  end
end

When run the output is:

运行时输出为:

calling other method with var = 6
this is my block
finished other method with var = 6
calling other method with var = 3
finished other method with var = 3

#2


2  

Yes, it is possible. In fact, the code you posted already works just fine as-is.

是的,这是可能的。事实上,您发布的代码已经可以正常工作了。