首页 文章

Ruby - lambda vs. Proc.new [复制]

提问于
浏览
36

可能重复:Ruby中的proc和lambda有什么区别?

运行此 Ruby 代码时:

def func_one
    proc_new = Proc.new {return "123"}
    proc_new.call
    return "456"
end

def func_two
    lambda_new = lambda {return "123"}
    lambda_new.call
    return "456"
end

puts "The result of running func_one is " + func_one
puts ""
puts "The result of running func_two is " + func_two

我得到的结果如下:

The result of running func_one is 123

The result of running func_two is 456

至于 func_twofirst return 的值在哪里,即 123

谢谢 .

3 回答

  • 27

    这是Procs和lambdas之间的主要区别之一 .

    Proc中的返回从其封闭块/方法返回,而lambda中的返回仅从lambda返回 . 当你在func_two中调用lambda时,它只是返回它的值,而不是保存它 .

    请阅读Procs v.lambdas:http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls

    看到重复的SO问题:Why does explicit return make a difference in a Proc?

    编辑:

    为了进一步说明这种差异,请将func_one和func_two换成块,看看会发生什么:

    > begin; lambda { return 1 }.call end
    1
    > begin; Proc.new { return 1 }.call end
    LocalJumpError: unexpected return
    ...
    
  • 4

    在proc中, return "123" 正在冒泡并从外部函数 func_one 返回 . 因此,永远不会遇到第二个return语句 .

    在lambda中, return "123" 仅从lambda返回 . 你没有将变量设置为lambda的返回值(当你执行 lambda_new.call 时,所以该值基本上被抛出 . 然后, return "456" 被调用并从函数返回 . 如果,而不是返回 "456" ,则返回 lambda_new.callfunc_two 的返回值为 "123" .

  • 0

    123lambda_new.call 语句的值,但未使用且未显示 .

相关问题