Uniq by object attribute in Ruby

前端 未结 14 1781
我寻月下人不归
我寻月下人不归 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-11-30 23:46

    You can use a hash, which contains only one value for each key:

    Hash[*recs.map{|ar| [ar[attr],ar]}.flatten].values
    

提交回复
热议问题