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

后端 未结 6 520
逝去的感伤
逝去的感伤 2021-01-30 12:02

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 = [         


        
6条回答
  •  无人共我
    2021-01-30 12:44

    Important to keep in mind that the Set class and the | method (also called "Set Union") will yield an array of unique elements, which is great if you want no duplicates but which will be an unpleasant surprise if you have non-unique elements in your original array by design.

    If you have at least one duplicate element in your original array that you don't want to lose, iterating through the array with an early return is worst-case O(n), which isn't too bad in the grand scheme of things.

    class Array
      def add_if_unique element
        return self if include? element
        push element
      end
    end
    

提交回复
热议问题