Ruby: proc {}.arity – a second go…

arity returns the number of arguments that would not be ignored.

e.g. if the block is declared to take 0 arguments it returns 0.

If the block takes n arguments, it returns n.

If the block takes optional arguments it returns -n-1 where n is the number of mandatory arguments.

e.g. 

proc {}.arity          #=>  0

proc {||}.arity        #=>  0

proc {|a|}.arity       #=>  1

proc {|a,b|}.arity     #=>  2

proc {|a,b,c|}.arity   #=>  3

proc {|*a|}.arity      #=> -1

proc {|a,*b|}.arity    #=> -2

proc {|a,*b, c|}.arity #=> -3

Note that:

proc{|a=1||}.arity #=> 0

This is because the a is now optional.

http://www.ruby-doc.org/core-2.0/Proc.html#method-i-arity

And for proc vs lambda.arity

e.g. 

proc   { |x = 0| }.arity       #=> 0

lambda { |a = 0| }.arity       #=> -1

proc   { |x=0, y| }.arity      #=> 1

lambda { |x=0, y| }.arity      #=> -2

Leave a Reply

Your email address will not be published. Required fields are marked *