简体   繁体   English

Ruby:将Proc传递给无参数的方法

[英]Ruby: Passing a Proc to method with no parameters

So this works(Pulled from Code-Academy): 所以这可行(从Code-Academy拉出):

def greeter
  yield
end

phrase = Proc.new {
  puts "Hello there!"
  }

greeter(&phrase)

I understand what yield is doing, and understand what a Proc does. 我了解产量在做什么,并且了解Proc在做什么。 However "why" is this allowed? 但是“为什么”被允许?

IE: greeter method has no parameters defined, not even optional ones. IE: greeter方法没有定义参数,甚至没有可选参数。 So why does ruby allow us to pass something to it? 那么为什么红宝石能让我们传递一些东西呢? (In this case a reference to a block of code (The Proc phrase ). (在这种情况下,对代码块的引用(Proc phrase )。

I mean it's great that it does, but rule-wise this seems like it shouldn't be allowed? 我的意思是这样做很棒,但是从规则上来说,这似乎不应该被允许吗?

&phrase is not a reference. &phrase不是参考。 It is the Ruby annotation for passing a block explicitly. 它是用于显式传递块的Ruby注释。 Here , it is converting the proc to the implicit block for the method call. 在这里,它将proc转换为方法调用的隐式块。 Since every method accepts a default block as an argument, your code works. 由于每个方法都接受默认块作为参数,因此您的代码有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM