gpt4 book ai didi

ruby - 为什么 Enumerable#detect 需要 Proc/lambda?

转载 作者:数据小太阳 更新时间:2023-10-29 06:44:07 26 4
gpt4 key购买 nike

Enumerable#detect 返回 block 评估为 true 的数组的第一个值。它有一个可选参数,需要响应 call 并在这种情况下被调用,返回它的值。所以,

(1..10).detect(lambda{ "none" }){|i| i == 11} #=> "none"

为什么我们需要 lambda?为什么我们不直接传递默认值本身,因为(在我的测试中)lambda 无论如何都不能有任何参数?像这样:

(1..10).detect("none"){|i| i == 11} #=> "none"

最佳答案

与 Ruby 中的所有事物一样,“最小意外原则”适用。当然,这并不是说“对您来说最不意外”。 Matz 对 what it actually means 很坦诚:

Everyone has an individual background. Someone may come from Python, someone else may come from Perl, and they may be surprised by different aspects of the language. Then they come up to me and say, 'I was surprised by this feature of the language, so Ruby violates the principle of least surprise.' Wait. Wait. The principle of least surprise is not for you only. The principle of least surprise means principle of least my surprise. And it means the principle of least surprise after you learn Ruby very well. For example, I was a C++ programmer before I started designing Ruby. I programmed in C++ exclusively for two or three years. And after two years of C++ programming, it still surprises me.

所以,这里的合理性真的是任何人的猜测。

一种可能性是它允许或符合您想要有条件地运行昂贵的东西的用例:

arr.detect(lambda { do_something_expensive }) { |i| is_i_ok? i }

或者如@majioa 所暗示的那样,也许传递一个方法:

arr.detect(method(:some_method)) { |i| is_i_ok? i }

关于ruby - 为什么 Enumerable#detect 需要 Proc/lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20883414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com