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?
The unshift() method is used to add one or multiple elements to the beginning of an array. It returns the length of the new array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the beginning of the array.
Another way to add/insert an element into an array is to use the . splice() method. With . splice() you can insert a new element at any given index, either overwriting what is currently in that index number, or inserting within, with no overwriting.
When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().
The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With