Uniq by object attribute in Ruby

前端 未结 14 1783
我寻月下人不归
我寻月下人不归 2020-11-30 23:20

What\'s the most elegant way to select out objects in an array that are unique with respect to one or more attributes?

These objects are stored in ActiveRecord so us

相关标签:
14条回答
  • 2020-12-01 00:01

    I like jmah's use of a Hash to enforce uniqueness. Here's a couple more ways to skin that cat:

    objs.inject({}) {|h,e| h[e.attr]=e; h}.values
    

    That's a nice 1-liner, but I suspect this might be a little faster:

    h = {}
    objs.each {|e| h[e.attr]=e}
    h.values
    
    0 讨论(0)
  • 2020-12-01 00:02

    You can use this trick to select unique by several attributes elements from array:

    @photos = @photos.uniq { |p| [p.album_id, p.author_id] }
    
    0 讨论(0)
提交回复
热议问题