jay jay - 2 months ago 4x
Ruby Question

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

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?

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

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

if they were hash


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 }

And then do like :

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