I'm trying to set up a method that takes a block as a parameter. I know you do this by giving the last parameter an & prefix, but once it's been passed, how should I verify it?
If I want to verify that an argument is a string, I could use is_a?(String)
, for example. But how do I verify that I have received a block that accepts one parameter? Or 2?
You can use the Proc#arity
method to check how many arguments the block accepts:
def foo(&block)
puts block.arity
end
foo { } # => 0
foo { |a| } # => 1
foo { |a, b| } # => 2
From the documentation:
Returns the number of arguments that would not be ignored. If the block is declared to take no arguments, returns 0. If the block is known to take exactly n arguments, returns n. If the block has optional arguments, return -n-1, where n is the number of mandatory arguments. A proc with no argument declarations is the same a block declaring || as its arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With