Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-mutating array push method equivalent

Tags:

arrays

ruby

I'd like to add a new element to an array in a non-mutating way. In JS, I can do this:

var new_arr = arr.concat(3)

instead of this:

arr.push(3)

How can I do the same thing in Ruby? The concat method in Ruby is mutating.

like image 607
Karol Selak Avatar asked Dec 03 '22 20:12

Karol Selak


2 Answers

As simple as this:

new_arr = arr + [3]
like image 154
Sergio Tulentsev Avatar answered Jan 16 '23 03:01

Sergio Tulentsev


I'll add another solution using array splats that might seem less awkward:

new_arr = [*arr, 3]
like image 33
Brian Kung Avatar answered Jan 16 '23 01:01

Brian Kung