新手问题 关于 proc/lambda 对象的 arity 方法返回数量不对的问题

ailms · October 21, 2012 · Last by iBachue replied at April 22, 2013 · 2401 hits

irb(main):067:0> lambda{|x=2,y| x+y}.arity => 0 irb(main):068:0> lambda{|x,y=2| x+y}.arity
=> 1 irb(main):069:0>

bob@bob-ruby:~$ ruby --version ruby 1.9.3p194 (2012-04-20 revision 35410) [i686-linux] bob@bob-ruby:~$

为什么第一个返回的必须的参数是 0 个呢?

The Ruby programming

In Ruby 1.8, method parameters with default values must appear after all ordinary parameters in the parameter list. Ruby 1.9 relaxes this restriction and allows ordinary parameters to appear after parameters with defaults

貌似 Proc 的 arity 只会 返回 有 默认值的参数前面的参数的个数,后面一概不管。

Proc.new{|d,a=1,b,c|}.arity
=>1

Method 的 arity 则不同,规则和 有 *options 参数类似,返回 -n-1

def foo(a,b=1);end
=>nil
method(:foo).arity
=>-2

并且 有默认值的参数和*options 的参数不管出现多少次都算 -1,

def foo(a,b=1,*c);end
=>nil
method(:foo).arity
=>-2

具体什么规律不太清楚。

http://ruby-doc.org/core-2.0/Proc.html#method-i-arity 这里列的很详细 但是缺乏 method 部分的结果 所以还是完全摸不到规则。。

You need to Sign in before reply, if you don't have an account, please Sign up first.