sujay
sujay

Reputation: 681

Remove duplicates from array of objects based on multiple attributes in ruby

I have an array of objects which may contain objects with same attribute values. I am trying to remove the duplicates based on multiple attributes (not just one attribute value)

class Font
 attr_accessor :color, :name, :type
end

a = <@color="blue", @name="s", @type="bold">
b = <@color="blue", @name="r", @type="italic"> 
c = <@color="green", @name="t", @type="bold">
d = <@color="blue", @name="s", @type="some_other_type">

fonts = [a, b, c, d]

I need to eliminate duplicates based on the values of color, name (I don't care about type)

what I have tried

uniq_fonts = fonts.uniq { |f| f.name.to_s + f.color.to_s}

is there any cleaner way in which I can achieve the same result?

Note: these are objects and not hashes. I know we could have used:

fonts.uniq { |f| f.values_at(:name, :color)}

if they were hash

Upvotes: 4

Views: 4403

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118271

You can try:

uniq_fonts = fonts.uniq { |f| [ f.name, f.color ] }

You can defined your own values_at method like:

class Font
  attr_accessor :color, :name, :type

  def values_at *args
    args.map { |method_name| self.public_send method_name }
  end
end

And then do like :

fonts.uniq { |f| f.values_at(:name, :color)}

Upvotes: 15

Related Questions