1
我該怎麼做?現在當用戶是男性時,它創建了無值,然後< ==>操作失敗。如果你需要過濾值的話,你如何使用max_by和enumerable?
@user.max_by{|user_id, user| user.height if user.female?}
我該怎麼做?現在當用戶是男性時,它創建了無值,然後< ==>操作失敗。如果你需要過濾值的話,你如何使用max_by和enumerable?
@user.max_by{|user_id, user| user.height if user.female?}
你可以連續使用這些結合在一起,使你的聚合前做好選擇
@user.select{|user| user.female?}.max_by{|user_id, user| user.height}
此外,你應該能夠簡化(只是一點點的語法糖):
@user.select(&:female?).max_by(&:height)
酷,你在第二個例子中使用的過程叫做什麼?我想了解更多。謝謝! – 2011-06-05 17:59:34
第二個例子是使用[Symbol#to_proc](http://www.ruby-doc.org/core/classes/Symbol.src/M000780.html)。請注意,與某些版本中的標準塊相比,它會[速度相當慢](http://blog.gregspurrier.com/articles/relative-performance-of-symbol-to-proc-in-popular-ruby-implementations)的Ruby。 – 2011-06-05 18:15:51
@格雷格坎貝爾 - 優秀的職位......任何讀這篇文章的人都應該閱讀該鏈接。標題對我來說:ruby 1.8.7和1.9.2都可以使用上面的語法。如果您使用另一個,請檢查鏈接。 – 2011-06-06 00:48:47