Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add element to ruby array return new array

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?

like image 983
srchulo Avatar asked Jan 31 '12 00:01

srchulo


People also ask

How do you add an element to an array in Ruby?

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.

How do you add an array to an array in Ruby?

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.

How do you add an element to a new array?

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.


2 Answers

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] 
like image 108
Sergio Tulentsev Avatar answered Sep 27 '22 20:09

Sergio Tulentsev


it also works by extending arr using * operator

arr = [1,2] puts [*arr, 3] => [1, 2, 3] 
like image 37
kazuwombat Avatar answered Sep 27 '22 18:09

kazuwombat