此代码按预期工作(不执行任何操作,甚至不会产生警告/错误):
l = lambda {|i|}
l.call(1)
Run Code Online (Sandbox Code Playgroud)
此代码生成警告(警告:块参数的多个值(0表示1)):
l = lambda {|i|}
l.call
Run Code Online (Sandbox Code Playgroud)
并且此代码失败并出现错误(ArgumentError:错误的参数数量(0表示2)):
l = lambda {|i, y|}
l.call
Run Code Online (Sandbox Code Playgroud)
我认为lambda需要传递所有参数.
从第二个例子我发现它不是.为什么只给出一个参数,并且按预期工作(失败并带有错误)并且有多个参数?
PS:ruby 1.8.6(2008-08-11 patchlevel 287)[universal-darwin9.0]
更新:我用ruby 1.9.1p376检查了这些样本.它按预期工作 - 第二个例子也产生错误.看起来这是1.8版本(或<= 1.8)的功能
Tre*_*oke 13
这个脚本将教你在Ruby中关于闭包的所有知识.
# So, what's the final verdict on those 7 closure-like entities?
#
# "return" returns from closure
# True closure? or declaring context...? Arity check?
# --------------- ----------------------------- -------------------
# 1. block (called with yield) N declaring no
# 2. block (&b => f(&b) => yield) N declaring no
# 3. block (&b => b.call) Y except return declaring warn on too few
# 4. Proc.new Y except return declaring warn on too few
# 5. proc <<< alias for lambda in 1.8, Proc.new in 1.9 >>>
# 6. lambda Y closure yes, except arity 1
# 7. method Y closure yes
Run Code Online (Sandbox Code Playgroud)
当lambda期望参数并且我们不提供它们,或者我们提供错误数量的参数时,抛出异常.
l = lambda { |name| puts "Today we will practice #{name} meditation." }
l.call
ArgumentError: wrong number of arguments (given 0, expected 1)
Run Code Online (Sandbox Code Playgroud)
我们可以使用arity方法找出预期参数的数量:
l.arity # Output: => 1
Run Code Online (Sandbox Code Playgroud)
就像方法一样,lambda接受所有以下类型的参数/参数:
以下示例说明了采用多种类型参数的lambda的语法.
# Stabby syntax
l = -> (cushion, meditation="kinhin", *room_items, time:, posture: "kekkafuza", **periods, &p) do
p.call
end
# Regular syntax
l = lambda do |cushion, meditation="kinhin", *room_items, time:, posture: "kekkafuza", **periods, &p|
p.call
end
l.call("zafu", "zazen", "zabuton", "incense", time: 40, period1: "morning", period2: "afternoon" ) { puts "Hello from inside the block, which is now a proc." }
Output:
Hello from inside the block, which is now a proc.
Run Code Online (Sandbox Code Playgroud)
Lambdas以与方法相同的方式处理参数.在这篇关于方法的博客文章中,对所有上述参数/参数类型有一个全面的解释.