4

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

3
  • 1
    Why the rush to select an answer? You may discourage other answers and short-circuit those still preparing answers. Commented Aug 10, 2016 at 18:26
  • 1
    a, b, c and d are not valid objects, so readers cannot test without going to the trouble of modifying your code. You need to add def initialize(color, name, type); @color, @name, @type = color, name, type; end, define a = Font("blue", "s", "bold") and similar for b, c and d. Commented Aug 10, 2016 at 18:30
  • I mean a = Font.new("blue", "s", "bold")... Commented Aug 10, 2016 at 21:48

1 Answer 1

15

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)}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.