user13308268
user13308268

Reputation: 11

why proc doesn't need to have a default value if it is an optional argument in ruby

In ruby, if an argument is optional, we should give this argument an default value in the definition, the definition is like below:

def my_function(var = 1)
end

However, if I have a function definition like below, it looks like this function should receive one argument and this argument is a proc, my question is why there is no error if this method is called without a parameter? If this proc argument is optional, why it has no default value?

def my_function(&prc)
end
p my_function

Upvotes: 1

Views: 159

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369468

In Ruby, every method implicitly has a single optional block parameter. The & unary prefix ampersand sigil means "take the block that was passed as an argument, roll it up into a Proc object, and bind it to this parameter". Since every block parameter is always optional, and there can be only one, there is no need to explicitly mark it as optional. We already know it is.

Upvotes: 1

Related Questions