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

Ruby

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

@Coorasse has a good answer, though it should be:

my_array | [item]

And to update my_array in place:

my_array |= [item]

Solution 2 - Ruby

You can use Set instead of Array.

Solution 3 - Ruby

You don't need to iterate through my_array by hand.

my_array.push(item1) unless my_array.include?(item1)

Edit:

As Tombart points out in his comment, using Array#include? is not very efficient. I'd say the performance impact is negligible for small Arrays, but you might want to go with Set for bigger ones.

Solution 4 - Ruby

You can convert item1 to array and join them:

my_array | [item1]

Solution 5 - Ruby

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

Solution 6 - Ruby

I'm not sure if it's perfect solution, but worked for me:

    host_group = Array.new if not host_group.kind_of?(Array)
    host_group.push(host)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlan CoromanoView Question on Stackoverflow
Solution 1 - RubyJason DenneyView Answer on Stackoverflow
Solution 2 - RubyJiří PospíšilView Answer on Stackoverflow
Solution 3 - RubydoesterrView Answer on Stackoverflow
Solution 4 - RubycoorasseView Answer on Stackoverflow
Solution 5 - RubyelreimundoView Answer on Stackoverflow
Solution 6 - Rubywitkacy26View Answer on Stackoverflow