srchulo
srchulo

Reputation: 5203

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?

Upvotes: 47

Views: 23975

Answers (2)

kazuwombat
kazuwombat

Reputation: 1663

it also works by extending arr using * operator

arr = [1,2]
puts [*arr, 3]
=> [1, 2, 3]

Upvotes: 16

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

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]

Upvotes: 57

Related Questions