加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 为什么Enumerable#detect需要一个Proc / lambda?

发布时间:2020-12-16 21:48:18 所属栏目:百科 来源:网络整理
导读:Enumerable#detect返回块计算结果为true的数组的第一个值.它有一个可选参数,需要响应调用,并在这种情况下被调用,返回其值.所以, (1..10).detect(lambda{ "none" }){|i| i == 11} #= "none" 为什么我们需要lambda?为什么我们不传递默认值本身,因为(在我的测
Enumerable#detect返回块计算结果为true的数组的第一个值.它有一个可选参数,需要响应调用,并在这种情况下被调用,返回其值.所以,
(1..10).detect(lambda{ "none" }){|i| i == 11} #=> "none"

为什么我们需要lambda?为什么我们不传递默认值本身,因为(在我的测试中),lambda不能有任何参数?喜欢这个:

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

解决方法

与Ruby中的所有内容一样,“最小惊奇的原则”也适用.当然不是说“最不惊喜”.马茨对 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 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读