何时使用 lambda,何时使用 Proc.new?

发布于 2024-07-04 00:15:35 字数 185 浏览 6 评论 0原文

在 Ruby 1.8 中,一方面 proc/lambda 与 Proc.new 之间存在细微差别。

  • 这些差异是什么?
  • 您能否给出如何决定选择哪一个的指南?
  • 在 Ruby 1.9 中,proc 和 lambda 是不同的。 这是怎么回事?

In Ruby 1.8, there are subtle differences between proc/lambda on the one hand, and Proc.new on the other.

  • What are those differences?
  • Can you give guidelines on how to decide which one to choose?
  • In Ruby 1.9, proc and lambda are different. What's the deal?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

孤独陪着我 2024-07-11 00:15:35

值得强调的是,过程中的return从词法封闭的方法返回,即创建过程的方法而不是调用的方法程序。 这是 procs 的闭包属性的结果。 因此,以下代码不会输出任何内容:

def foo
  proc = Proc.new{return}
  foobar(proc)
  puts 'foo'
end

def foobar(proc)
  proc.call
  puts 'foobar'
end

foo

虽然 proc 在 foobar 中执行,但它是在 foo 中创建的,因此 return 退出 foo< /code>,而不仅仅是 foobar。 正如 Charles Caldwell 上面所写,它有一种 GOTO 的感觉。 在我看来,return 在其词法上下文中执行的块中很好,但在不同上下文中执行的过程中使用时就不太直观了。

It's worth emphasizing that return in a proc returns from the lexically enclosing method, i.e. the method where the proc was created, not the method that called the proc. This is a consequence of the closure property of procs. So the following code outputs nothing:

def foo
  proc = Proc.new{return}
  foobar(proc)
  puts 'foo'
end

def foobar(proc)
  proc.call
  puts 'foobar'
end

foo

Although the proc executes in foobar, it was created in foo and so the return exits foo, not just foobar. As Charles Caldwell wrote above, it has a GOTO feel to it. In my opinion, return is fine in a block that is executed in its lexical context, but is much less intuitive when used in a proc that is executed in a different context.

夜唯美灬不弃 2024-07-11 00:15:35

提供进一步说明:

Joey 说 Proc.new 的返回行为令人惊讶。 然而,当您考虑到 Proc.new 的行为类似于块时,这并不奇怪,因为这正是块的行为方式。 另一方面,lambas 的行为更像方法。

这实际上解释了为什么 Proc 在 arity(参数数量)方面很灵活,而 lambda 则不然。 块不需要提供所有参数,但方法需要提供(除非提供默认值)。 虽然提供 lambda 参数默认值在 Ruby 1.8 中不是一个选项,但现在 Ruby 1.9 中通过替代 lambda 语法(如 webmat 所指出的)支持它:

concat = ->(a, b=2){ "#{a}#{b}" }
concat.call(4,5) # => "45"
concat.call(1)   # => "12"

并且 Michiel de Mare(OP)关于 Procs 和 lambda 行为相同的说法是不正确的Ruby 1.9 中具有 arity。 我已验证它们仍然保持上述 1.8 中指定的行为。

break 语句实际上在 Procs 或 lambda 中没有多大意义。 在 Procs 中,中断将使您从已经完成的 Proc.new 返回。 打破 lambda 没有任何意义,因为它本质上是一个方法,而且你永远不会打破方法的顶层。

nextredoraise 在 Procs 和 lambda 中的行为相同。 而 retry 两者都是不允许的,并且会引发异常。

最后,永远不应该使用 proc 方法,因为它不一致并且具有意外的行为。 在 Ruby 1.8 中它实际上返回一个 lambda! 在 Ruby 1.9 中,这个问题已被修复并返回一个 Proc。 如果您想创建一个 Proc,请坚持使用 Proc.new

要了解更多信息,我强烈推荐 O'Reilly 的《The Ruby Programming Language》,它是我大部分信息的来源。

To provide further clarification:

Joey says that the return behavior of Proc.new is surprising. However when you consider that Proc.new behaves like a block this is not surprising as that is exactly how blocks behave. lambas on the other hand behave more like methods.

This actually explains why Procs are flexible when it comes to arity (number of arguments) whereas lambdas are not. Blocks don't require all their arguments to be provided but methods do (unless a default is provided). While providing lambda argument default is not an option in Ruby 1.8, it is now supported in Ruby 1.9 with the alternative lambda syntax (as noted by webmat):

concat = ->(a, b=2){ "#{a}#{b}" }
concat.call(4,5) # => "45"
concat.call(1)   # => "12"

And Michiel de Mare (the OP) is incorrect about the Procs and lambda behaving the same with arity in Ruby 1.9. I have verified that they still maintain the behavior from 1.8 as specified above.

break statements don't actually make much sense in either Procs or lambdas. In Procs, the break would return you from Proc.new which has already been completed. And it doesn't make any sense to break from a lambda since it's essentially a method, and you would never break from the top level of a method.

next, redo, and raise behave the same in both Procs and lambdas. Whereas retry is not allowed in either and will raise an exception.

And finally, the proc method should never be used as it is inconsistent and has unexpected behavior. In Ruby 1.8 it actually returns a lambda! In Ruby 1.9 this has been fixed and it returns a Proc. If you want to create a Proc, stick with Proc.new.

For more information, I highly recommend O'Reilly's The Ruby Programming Language which is my source for most of this information.

血之狂魔 2024-07-11 00:15:35

return 语句:

  • 使用 lambda 创建的过程和使用 Proc.new 创建的过程之间的另一个重要但微妙的区别是它们如何处理 >lambda 创建的过程,return 语句仅从过程本身返回
  • Proc.new 创建的过程中,return > 语句有点令人惊讶:它不仅从 proc 返回控制,还从包含该 proc 的方法返回控制!

这是 lambda 创建的 proc 的 return< /code> 正在行动。 它的行为方式可能符合您的预期:

def whowouldwin

  mylambda = lambda {return "Freddy"}
  mylambda.call

  # mylambda gets called and returns "Freddy", and execution
  # continues on the next line

  return "Jason"

end


whowouldwin
#=> "Jason"

现在这是一个 Proc.new 创建的 proc 的 return 执行相同的操作。 您将看到 Ruby 打破了大肆吹嘘的最小意外原则的情况之一:

def whowouldwin2

  myproc = Proc.new {return "Freddy"}
  myproc.call

  # myproc gets called and returns "Freddy", 
  # but also returns control from whowhouldwin2!
  # The line below *never* gets executed.

  return "Jason"

end


whowouldwin2         
#=> "Freddy"

由于这种令人惊讶的行为(以及更少的打字),我倾向于使用 lambda 而不是 < code>Proc.new 制作过程时。

Another important but subtle difference between procs created with lambda and procs created with Proc.new is how they handle the return statement:

  • In a lambda-created proc, the return statement returns only from the proc itself
  • In a Proc.new-created proc, the return statement is a little more surprising: it returns control not just from the proc, but also from the method enclosing the proc!

Here's lambda-created proc's return in action. It behaves in a way that you probably expect:

def whowouldwin

  mylambda = lambda {return "Freddy"}
  mylambda.call

  # mylambda gets called and returns "Freddy", and execution
  # continues on the next line

  return "Jason"

end


whowouldwin
#=> "Jason"

Now here's a Proc.new-created proc's return doing the same thing. You're about to see one of those cases where Ruby breaks the much-vaunted Principle of Least Surprise:

def whowouldwin2

  myproc = Proc.new {return "Freddy"}
  myproc.call

  # myproc gets called and returns "Freddy", 
  # but also returns control from whowhouldwin2!
  # The line below *never* gets executed.

  return "Jason"

end


whowouldwin2         
#=> "Freddy"

Thanks to this surprising behavior (as well as less typing), I tend to favor using lambda over Proc.new when making procs.

蓝眼睛不忧郁 2024-07-11 00:15:35

Proc 较旧,但 return 的语义对我来说非常违反直觉(至少在我学习该语言时),因为:

  1. 如果您使用 proc,您很可能使用某种函数范式。
  2. Proc 可以从封闭范围返回(请参阅之前的响应),这基本上是一个 goto,本质上是高度非功能性的。

Lambda 在功能上更安全,更容易推理——我总是使用它而不是 proc。

Proc is older, but the semantics of return are highly counterintuitive to me (at least when I was learning the language) because:

  1. If you are using proc, you are most likely using some kind of functional paradigm.
  2. Proc can return out of the enclosing scope (see previous responses), which is a goto basically, and highly non-functional in nature.

Lambda is functionally safer and easier to reason about - I always use it instead of proc.

听闻余生 2024-07-11 00:15:35

我发现此页面显示了Proc.new之间的区别>lambda 是。 根据该页面,唯一的区别是 lambda 对它接受的参数数量很严格,而 Proc.new 将缺少的参数转换为 nil。 以下是说明差异的 IRB 会话示例:

irb(main):001:0> l = lambda { |x, y| x + y }
=> #<Proc:0x00007fc605ec0748@(irb):1>
irb(main):002:0> p = Proc.new { |x, y| x + y }
=> #<Proc:0x00007fc605ea8698@(irb):2>
irb(main):003:0> l.call "hello", "world"
=> "helloworld"
irb(main):004:0> p.call "hello", "world"
=> "helloworld"
irb(main):005:0> l.call "hello"
ArgumentError: wrong number of arguments (1 for 2)
    from (irb):1
    from (irb):5:in `call'
    from (irb):5
    from :0
irb(main):006:0> p.call "hello"
TypeError: can't convert nil into String
    from (irb):2:in `+'
    from (irb):2
    from (irb):6:in `call'
    from (irb):6
    from :0

该页面还建议使用 lambda,除非您特别想要容错行为。 我同意这种观点。 使用 lambda 似乎更简洁一些,并且由于差异如此微不足道,因此在一般情况下它似乎是更好的选择。

至于 Ruby 1.9,抱歉,我还没有研究过 1.9,但我不认为他们会改变那么多(不过不要相信我的话,看来你已经听说过一些变化,所以我可能错了)。

I found this page which shows what the difference between Proc.new and lambda are. According to the page, the only difference is that a lambda is strict about the number of arguments it accepts, whereas Proc.new converts missing arguments to nil. Here is an example IRB session illustrating the difference:

irb(main):001:0> l = lambda { |x, y| x + y }
=> #<Proc:0x00007fc605ec0748@(irb):1>
irb(main):002:0> p = Proc.new { |x, y| x + y }
=> #<Proc:0x00007fc605ea8698@(irb):2>
irb(main):003:0> l.call "hello", "world"
=> "helloworld"
irb(main):004:0> p.call "hello", "world"
=> "helloworld"
irb(main):005:0> l.call "hello"
ArgumentError: wrong number of arguments (1 for 2)
    from (irb):1
    from (irb):5:in `call'
    from (irb):5
    from :0
irb(main):006:0> p.call "hello"
TypeError: can't convert nil into String
    from (irb):2:in `+'
    from (irb):2
    from (irb):6:in `call'
    from (irb):6
    from :0

The page also recommends using lambda unless you specifically want the error tolerant behavior. I agree with this sentiment. Using a lambda seems a tad more concise, and with such an insignificant difference, it seems the better choice in the average situation.

As for Ruby 1.9, sorry, I haven't looked into 1.9 yet, but I don't imagine they would change it all that much (don't take my word for it though, it seems you have heard of some changes, so I am probably wrong there).

泛滥成性 2024-07-11 00:15:35

对于细微的差别我不能说太多。 不过,我可以指出,Ruby 1.9 现在允许 lambda 和块使用可选参数。

以下是 1.9 下的 stable lambda 的新语法:

stabby = ->(msg='inside the stabby lambda') { puts msg }

Ruby 1.8 没有该语法。 声明块/lambda 的传统方式也不支持可选参数:

# under 1.8
l = lambda { |msg = 'inside the stabby lambda'|  puts msg }
SyntaxError: compile error
(irb):1: syntax error, unexpected '=', expecting tCOLON2 or '[' or '.'
l = lambda { |msg = 'inside the stabby lambda'|  puts msg }

然而,Ruby 1.9 即使使用旧语法也支持可选参数:

l = lambda { |msg = 'inside the regular lambda'|  puts msg }
#=> #<Proc:0x0e5dbc@(irb):1 (lambda)>
l.call
#=> inside the regular lambda
l.call('jeez')
#=> jeez

如果您想为 Leopard 或 Linux 构建 Ruby1.9,请查看 这篇文章(无耻的自我推销)。

I can't say much about the subtle differences. However, I can point out that Ruby 1.9 now allows optional parameters for lambdas and blocks.

Here's the new syntax for the stabby lambdas under 1.9:

stabby = ->(msg='inside the stabby lambda') { puts msg }

Ruby 1.8 didn't have that syntax. Neither did the conventional way of declaring blocks/lambdas support optional args:

# under 1.8
l = lambda { |msg = 'inside the stabby lambda'|  puts msg }
SyntaxError: compile error
(irb):1: syntax error, unexpected '=', expecting tCOLON2 or '[' or '.'
l = lambda { |msg = 'inside the stabby lambda'|  puts msg }

Ruby 1.9, however, supports optional arguments even with the old syntax:

l = lambda { |msg = 'inside the regular lambda'|  puts msg }
#=> #<Proc:0x0e5dbc@(irb):1 (lambda)>
l.call
#=> inside the regular lambda
l.call('jeez')
#=> jeez

If you wanna build Ruby1.9 for Leopard or Linux, check out this article (shameless self promotion).

弃爱 2024-07-11 00:15:35

Ruby 中的闭包 很好地概述了块、lambda 和 proc 的工作方式使用 Ruby 工作,使用 Ruby。

Closures in Ruby is a good overview for how blocks, lambda and proc work in Ruby, with Ruby.

雪化雨蝶 2024-07-11 00:15:35

观察它的一个好方法是 lambda 是在自己的作用域中执行的(就好像它是一个方法调用),而 Procs 可以被视为与调用方法内联执行,至少这是决定使用哪一个的好方法在每种情况下。

A good way to see it is that lambdas are executed in their own scope (as if it was a method call), while Procs may be viewed as executed inline with the calling method, at least that's a good way of deciding wich one to use in each case.

抽个烟儿 2024-07-11 00:15:35

简短的回答:重要的是 return 的作用:lambda 从自身返回,而 proc 从自身以及调用它的函数返回。

不太清楚的是为什么要使用它们。 lambda 是我们期望的事情在函数式编程意义上应该做的事情。 它基本上是一个自动绑定当前范围的匿名方法。 在这两者中,lambda 是您可能应该使用的一个。

另一方面,Proc 对于实现语言本身确实非常有用。 例如,您可以使用它们实现“if”语句或“for”循环。 在过程中找到的任何返回都将从调用它的方法中返回,而不仅仅是“if”语句。 这就是语言的工作原理,“if”语句的工作原理,所以我猜测 Ruby 在幕后使用了它,他们只是暴露了它,因为它看起来很强大。

仅当您正在创建新的语言结构(例如循环、if-else 结构等)时,您才真正需要它。

Short answer: What matters is what return does: lambda returns out of itself, and proc returns out of itself AND the function that called it.

What is less clear is why you want to use each. lambda is what we expect things should do in a functional programming sense. It is basically an anonymous method with the current scope automatically bound. Of the two, lambda is the one you should probably be using.

Proc, on the other hand, is really useful for implementing the language itself. For example you can implement "if" statements or "for" loops with them. Any return found in the proc will return out of the method that called it, not the just the "if" statement. This is how languages work, how "if" statements work, so my guess is Ruby uses this under the covers and they just exposed it because it seemed powerful.

You would only really need this if you are creating new language constructs like loops, if-else constructs, etc.

面如桃花 2024-07-11 00:15:35

我没有注意到问题中第三种方法“proc”的任何评论,该方法已被弃用,但在 1.8 和 1.9 中处理方式不同。

这是一个相当详细的示例,可以轻松看出三个相似调用之间的差异:

def meth1
  puts "method start"

  pr = lambda { return }
  pr.call

  puts "method end"  
end

def meth2
  puts "method start"

  pr = Proc.new { return }
  pr.call

  puts "method end"  
end

def meth3
  puts "method start"

  pr = proc { return }
  pr.call

  puts "method end"  
end

puts "Using lambda"
meth1
puts "--------"
puts "using Proc.new"
meth2
puts "--------"
puts "using proc"
meth3

I didn't notice any comments on the third method in the queston, "proc" which is deprecated, but handled differently in 1.8 and 1.9.

Here's a fairly verbose example that makes it easy to see the differences between the three similar calls:

def meth1
  puts "method start"

  pr = lambda { return }
  pr.call

  puts "method end"  
end

def meth2
  puts "method start"

  pr = Proc.new { return }
  pr.call

  puts "method end"  
end

def meth3
  puts "method start"

  pr = proc { return }
  pr.call

  puts "method end"  
end

puts "Using lambda"
meth1
puts "--------"
puts "using Proc.new"
meth2
puts "--------"
puts "using proc"
meth3
天气好吗我好吗 2024-07-11 00:15:35

lambda 按预期工作,就像在其他语言中一样。

有线 Proc.new 令人惊讶且令人困惑。

Proc.new 创建的 proc 中的 return 语句不仅会从自身返回控制权,还会从包含它的方法返回控制权。

def some_method
  myproc = Proc.new {return "End."}
  myproc.call

  # Any code below will not get executed!
  # ...
end

您可以认为 Proc.new 将代码插入到封闭的方法中,就像 block 一样。
但是 Proc.new 创建一个对象,而 block 是对象的一部分。

lambda 和 Proc.new 之间还有另一个区别,那就是它们对(错误)参数的处理。
lambda 会对此进行抱怨,而 Proc.new 会忽略额外的参数或将缺少参数视为 nil。

irb(main):021:0> l = -> (x) { x.to_s }
=> #<Proc:0x8b63750@(irb):21 (lambda)>
irb(main):022:0> p = Proc.new { |x| x.to_s}
=> #<Proc:0x8b59494@(irb):22>
irb(main):025:0> l.call
ArgumentError: wrong number of arguments (0 for 1)
        from (irb):21:in `block in irb_binding'
        from (irb):25:in `call'
        from (irb):25
        from /usr/bin/irb:11:in `<main>'
irb(main):026:0> p.call
=> ""
irb(main):049:0> l.call 1, 2
ArgumentError: wrong number of arguments (2 for 1)
        from (irb):47:in `block in irb_binding'
        from (irb):49:in `call'
        from (irb):49
        from /usr/bin/irb:11:in `<main>'
irb(main):050:0> p.call 1, 2
=> "1"

顺便说一句,Ruby 1.8 中的 proc 创建了一个 lambda,而 Ruby 1.9+ 的行为类似于 Proc.new,这确实令人困惑。

lambda works as expected, like in other languages.

The wired Proc.new is surprising and confusing.

The return statement in proc created by Proc.new will not only return control just from itself, but also from the method enclosing it.

def some_method
  myproc = Proc.new {return "End."}
  myproc.call

  # Any code below will not get executed!
  # ...
end

You can argue that Proc.new inserts code into the enclosing method, just like block.
But Proc.new creates an object, while block are part of an object.

And there is another difference between lambda and Proc.new, which is their handling of (wrong) arguments.
lambda complains about it, while Proc.new ignores extra arguments or considers the absence of arguments as nil.

irb(main):021:0> l = -> (x) { x.to_s }
=> #<Proc:0x8b63750@(irb):21 (lambda)>
irb(main):022:0> p = Proc.new { |x| x.to_s}
=> #<Proc:0x8b59494@(irb):22>
irb(main):025:0> l.call
ArgumentError: wrong number of arguments (0 for 1)
        from (irb):21:in `block in irb_binding'
        from (irb):25:in `call'
        from (irb):25
        from /usr/bin/irb:11:in `<main>'
irb(main):026:0> p.call
=> ""
irb(main):049:0> l.call 1, 2
ArgumentError: wrong number of arguments (2 for 1)
        from (irb):47:in `block in irb_binding'
        from (irb):49:in `call'
        from (irb):49
        from /usr/bin/irb:11:in `<main>'
irb(main):050:0> p.call 1, 2
=> "1"

BTW, proc in Ruby 1.8 creates a lambda, while in Ruby 1.9+ behaves like Proc.new, which is really confusing.

醉城メ夜风 2024-07-11 00:15:35

我在这方面有点晚了,但是有一件关于 Proc.new 的伟大但鲜为人知的事情根本没有在评论中提及。 正如文档

Proc::new 可以在没有块的情况下仅在带有附加块的方法中调用,在这种情况下,块将转换为 Proc< /strong> 对象。


也就是说,Proc.new 可以链接生成方法:

def m1
  yield 'Finally!' if block_given?
end

def m2
  m1 &Proc.new
end

m2 { |e| puts e } 
#⇒ Finally!

I am a bit late on this, but there is one great but little known thing about Proc.new not mentioned in comments at all. As by documentation:

Proc::new may be called without a block only within a method with an attached block, in which case that block is converted to the Proc object.

That said, Proc.new lets to chain yielding methods:

def m1
  yield 'Finally!' if block_given?
end

def m2
  m1 &Proc.new
end

m2 { |e| puts e } 
#⇒ Finally!
坏尐絯 2024-07-11 00:15:35

详细说明 Accordion Guy 的响应:

请注意,Proc.new 通过传递一个块来创建一个 proc out。 我相信 lambda {...} 被解析为一种文字,而不是传递块的方法调用。 从附加到方法调用的块内部返回将从方法而不是块返回,Proc.new 情况就是一个例子。

(这是 1.8。我不知道如何转换为 1.9。)

To elaborate on Accordion Guy's response:

Notice that Proc.new creates a proc out by being passed a block. I believe that lambda {...} is parsed as a sort of literal, rather than a method call which passes a block. returning from inside a block attached to a method call will return from the method, not the block, and the Proc.new case is an example of this at play.

(This is 1.8. I don't know how this translates to 1.9.)

夜灵血窟げ 2024-07-11 00:15:35

恕我直言,return 的行为差异是两者之间最重要的差异。我也更喜欢 lambda,因为它比 Proc.new 打字更少:-)

The difference in behaviour with return is IMHO the most important difference between the 2. I also prefer lambda because it's less typing than Proc.new :-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文