I would like to add an element to an array but without actually changing that array and instead it returning a new one. In other words, I want to avoid:
arr = [1,2] arr << 3
Which would return:
[1,2,3]
Changing arr itself. How can I avoid this and create a new array?
unshift will add a new item to the beginning of an array. With insert you can add a new element to an array at any position.
When coding, there are times when you might want to join arrays to make them one. In this case, you can use the concat() method in Ruby. concat() is used to join, combine, concatenate, or append arrays. The concat() method returns a new array with all of the elements of the arrays combined into one.
By creating a new array:Create a new array of size n+1, where n is the size of the original array. Add the n elements of the original array in this array. Add the new element in the n+1 th position. Print the new array.
You can easily add two arrays in Ruby with plus
operator. So, just make an array out of your element.
arr = [1, 2] puts arr + [3] # => [1, 2, 3] puts arr # => [1, 2]
it also works by extending arr using * operator
arr = [1,2] puts [*arr, 3] => [1, 2, 3]
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