Uniq by object attribute in Ruby

前端 未结 14 1919
我寻月下人不归
我寻月下人不归 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:49

    I had originally suggested using the select method on Array. To wit:

    [1, 2, 3, 4, 5, 6, 7].select{|e| e%2 == 0} gives us [2,4,6] back.

    But if you want the first such object, use detect.

    [1, 2, 3, 4, 5, 6, 7].detect{|e| e>3} gives us 4.

    I'm not sure what you're going for here, though.

提交回复
热议问题