# 使用箭头语法的lambda hello_world = -> { 'Hello World!' } hello_world[] # '你好,世界!' # 使用箭头语法的lambda accepting 1 argument hello_world = ->(name) { "Hello #{name}!" } hello_world['Sven'] # "你好,斯文!" the_thing = lambda do |magic, ohai, dere| puts "magic! #{magic}" puts "ohai #{dere}" puts "#{ohai} means hello" end the_thing.call(1, 2, 3) #魔法!1 # 奥海3 # 2表示你好 the_thing.call(1, 2) # ArgumentError:参数数量错误(2个代表3个) the_thing[1, 2, 3, 4] # ArgumentError:参数数量错误(4个代表3个)
您还可以->用来创建和.()调用lambda
the_thing = ->(magic, ohai, dere) { puts "magic! #{magic}" puts "ohai #{dere}" puts "#{ohai} means hello" } the_thing.(1, 2, 3) # => magic! 1 # => ohai 3 # => 2 means hello
在这里,您可以看到lambda与proc几乎相同。但是,有一些警告:
强制执行lambda的论点;将错误数量的参数传递给lambda会引发ArgumentError。它们仍然可以具有默认参数,splat参数等。
return从lambda内部返回的结果是从lambda返回的,而return从proc返回的结果是在封闭范围之外的:
def try_proc
x =Proc.new{
return # 从try_proc返回
}
x.call
puts "After x.call" # 这条线永远不会到达
end
def try_lambda
y = -> {
return # 从y返回
}
y.call
puts "After y.call" # 此行不跳过
end
try_proc # 无输出
try_lambda # Outputs "After y.call"