Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: how to check how many parameters a block accepts?

Tags:

ruby

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?

like image 207
Mason Wheeler Avatar asked Dec 06 '22 04:12

Mason Wheeler


1 Answers

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.

like image 152
Renato Zannon Avatar answered Jan 17 '23 19:01

Renato Zannon