简体   繁体   中英

Ruby: Passing a Proc to method with no parameters

So this works(Pulled from 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. However "why" is this allowed?

IE: greeter method has no parameters defined, not even optional ones. So why does ruby allow us to pass something to it? (In this case a reference to a block of code (The 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. It is the Ruby annotation for passing a block explicitly. Here , it is converting the proc to the implicit block for the method call. Since every method accepts a default block as an argument, your code works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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