Created
October 8, 2010 02:48
-
-
Save moro/616296 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Enumerable | |
def detect_by(method, val) | |
detect{|obj| val == obj.__send__(method) } | |
end | |
end | |
p %w[a aa aaa aaaa aaaaa].detect_by(:length, 3) | |
# => aaa | |
# long example. Message.belongs_to :user | |
messages = Message.where(some_condition) | |
users_preload = User.where(:id => message.map(&:user_id).uniq) | |
messages.each do |m| | |
puts [message.text, users_preload.detect_by(:id, m.user_id).display_name] | |
# puts [message.text, users_preload.detect{|u| u.id == m.user_id }.display_name] | |
end |
↑ # を頭に書いたら強調されたww
む。Object#sendを使うという意味がよく分からない感じです。いま使ってるような。別のやり方?
あとブロックは釣りでしたごめんなさい。
用例で書いたけど
preloads = User.where(:id => [10, 11, 12]) preloads.detect_by(:id, 10) # should == preloads.detect {|u| u.id == 10 }
が嬉しいかな、と。
markdown記法のせいで __send__
周りの _(アンダーバー) が消えちゃってるのかと
oh!
oh! markdown!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
重箱の隅ですが、ライブラリとして使うなら Object#send を使ったようが良いと思いました!
また block とる場合は普通に ary.detect {|v| v.length > 3 } って書いた方が
解りやすいと思いました。
書き方の作法が余分に増えるよりはシンプルに統一されていた方がうれしい派