Uniq by object attribute in Ruby

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

    If I understand your question correctly, I've tackled this problem using the quasi-hacky approach of comparing the Marshaled objects to determine if any attributes vary. The inject at the end of the following code would be an example:

    class Foo
      attr_accessor :foo, :bar, :baz
    
      def initialize(foo,bar,baz)
        @foo = foo
        @bar = bar
        @baz = baz
      end
    end
    
    objs = [Foo.new(1,2,3),Foo.new(1,2,3),Foo.new(2,3,4)]
    
    # find objects that are uniq with respect to attributes
    objs.inject([]) do |uniqs,obj|
      if uniqs.all? { |e| Marshal.dump(e) != Marshal.dump(obj) }
        uniqs << obj
      end
      uniqs
    end
    

提交回复
热议问题