48

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?

2 Answers 2

57

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Why is there no way in ruby to add an item to an array with affecting the original array?
@gitb The array#+ method does this; it creates a new array from the left-hand side and the right-hand side of the plus operator and returns the new array, leaving both operands unmodified.
16

it also works by extending arr using * operator

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

1 Comment

For those coming from JS or familiarized with it, this syntax is equivalent to the spread operator: ` const arr = [1,2]; console.log([...arr, 3] => [1, 2, 3] `

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.