Add element to an array if it's not there already
@Coorasse has a good answer, though it should be:
my_array | [item]
And to update my_array
in place:
my_array |= [item]
You can use Set instead of Array.
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.