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.
As simple as this:
new_arr = arr + [3]
I'll add another solution using array splats that might seem less awkward:
new_arr = [*arr, 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