1

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?

1 Answer 1

2

&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.

Sign up to request clarification or add additional context in comments.

4 Comments

"Since every method accepts a default block as an argument, your code works." - I think since Im still new to ruby I didn't realize this. So you can always pass 1 block to a method? (I guess that makes sense, since we pass blocks to stuff like "map" and "collect" etc...). Can they accept more than 1 block by default out of curiosity?
@msmith1114 No. More than 1 block would cause ambiguity as to which block to yield to and thus raises a Syntax error. Methods can only receive 1 explicit block as well e.d def some_method(&block);end however you can pass as many block like objects (e.g. Proc, lambda, etc.) as the method arity will support
@engineersmnky Sorry maybe Im confused, your saying I can pass as many Procs/Lambdas as I want as parameters, but I can only pass one block to a method that's explicity defined like {whatever}?
@msmith1114, that is correct. You can think of Procs, lambdas and blocks to be blocks of code that can be passed around. Every method, be default, allows an optional block to be passed to it. Since Procs and lambdas can be named, you can pass around more than one. Check this example I created out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.