以下是我想傳遞任意參數給lambda
:
def with_arguments(&block)
args = %w(foo bar)
n = block.arity
block.call *(n < 0 ? args : args.take(n))
end
with_arguments &lambda { |foo| }
with_arguments &lambda { |foo, bar| }
with_arguments &lambda { |*args| }
with_arguments &lambda { |foo, *args| }
with_arguments &lambda { |foo, bar, *args| }
如果n
爲負數,那麼lambda
將接受任意數量的參數。這些參數的精確(n + 1).abs
是強制性的。可以使用該信息來決定要傳遞哪些參數。
如果lambda
需要有限數量的參數,那麼只需傳遞args
的第一個n
元素。如果它需要任意數量的參數,那麼只需傳遞整個參數數組。
的lambda
本身將處理情況args
不足:
with_arguments &lambda { |foo, bar, baz, *args| }
# ArgumentError: wrong number of arguments (2 for 3)
您可以將兩個參數簡單地傳遞到塊:
def with_arguments(&block)
block.call 'foo', 'bar'
end
with_arguments { |x| puts x } # y is not used
with_arguments { |x, y| puts x, y } # All arguments are used
with_arguments { |x, y, z| puts x, y, z } # z will be nil
不用塊參數被丟棄,任何額外的參數將被設置爲nil
。
This is specific to regular blocks and Proc
s - lambda
如果給定的參數數量錯誤,s會引發錯誤。實際上,你可以找出是否是這種情況通過調用Proc#lambda?
另外,如果你不打算來存儲塊,它是清潔,以簡單地使用yield
:
def with_arguments
yield 'foo', 'bar'
end
不你將這個方法分解爲'with_one_argument'和'with_two_arguments'(當然它們不會被稱爲那個)? – 2012-04-16 20:34:03