Skip to content

Instantly share code, notes, and snippets.

@moro
Created October 8, 2010 02:48
Show Gist options
  • Save moro/616296 to your computer and use it in GitHub Desktop.
Save moro/616296 to your computer and use it in GitHub Desktop.
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
@hotchpotch
Copy link

重箱の隅ですが、ライブラリとして使うなら Object#send を使ったようが良いと思いました!

また block とる場合は普通に ary.detect {|v| v.length > 3 } って書いた方が
解りやすいと思いました。

書き方の作法が余分に増えるよりはシンプルに統一されていた方がうれしい派

@hotchpotch
Copy link

↑ # を頭に書いたら強調されたww

@moro
Copy link
Author

moro commented Oct 8, 2010

む。Object#sendを使うという意味がよく分からない感じです。いま使ってるような。別のやり方?
あとブロックは釣りでしたごめんなさい。

用例で書いたけど

preloads = User.where(:id => [10, 11, 12])
preloads.detect_by(:id, 10)
# should == preloads.detect {|u| u.id == 10 }

が嬉しいかな、と。

@miyucy
Copy link

miyucy commented Oct 8, 2010

markdown記法のせいで __send__周りの _(アンダーバー) が消えちゃってるのかと

@moro
Copy link
Author

moro commented Oct 8, 2010

oh!

@hotchpotch
Copy link

oh! markdown!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment