當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby Proc.arity用法及代碼示例

本文簡要介紹ruby語言中 Proc.arity 的用法。

用法

arity → integer

返回強製參數的數量。如果該塊被聲明為不帶參數,則返回 0。如果已知該塊恰好帶 n 個參數,則返回 n。如果塊有可選參數,則返回 -n-1,其中 n 是強製參數的數量,但不是 lambda 且隻有有限數量的可選參數的塊除外;在後一種情況下,返回 n。關鍵字參數將被視為單個附加參數,如果任何關鍵字參數是強製性的,則該參數是強製性的。沒有參數聲明的 proc 與將 || 聲明為其參數的塊相同。

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
proc { |x:, y:, z:0| }.arity   #=>  1
proc { |*a, x:, y:0| }.arity   #=> -2

proc   { |a=0| }.arity         #=>  0
lambda { |a=0| }.arity         #=> -1
proc   { |a=0, b| }.arity      #=>  1
lambda { |a=0, b| }.arity      #=> -2
proc   { |a=0, b=0| }.arity    #=>  0
lambda { |a=0, b=0| }.arity    #=> -1
proc   { |a, b=0| }.arity      #=>  1
lambda { |a, b=0| }.arity      #=> -2
proc   { |(a, b), c=0| }.arity #=>  1
lambda { |(a, b), c=0| }.arity #=> -2
proc   { |a, x:0, y:0| }.arity #=>  1
lambda { |a, x:0, y:0| }.arity #=> -2

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Proc.arity。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。