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

前端之家收集整理的这篇文章主要介绍了ruby – 为什么Enumerable#detect需要一个Proc / 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 }

猜你在找的Ruby相关文章