Alan Coromano Alan Coromano - 25 days ago 11
Ruby Question

Add element to an array if it's not there already

I have a Ruby class

class MyClass
attr_writer :item1, :item2
end

my_array = get_array_of_my_class() #my_array is an array of MyClass
unique_array_of_item1 = []


I want to push
MyClass#item1
to
unique_array_of_item1
, but only if
unique_array_of_item1
doesn't contain that
item1
yet. There is a simple solution I know: just iterate through
my_array
and check if
unique_array_of_item1
already contains the current
item1
or not.

Is there any more efficient solution?

Answer

You can use Set instead of Array.

Comments