Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent side effects in Ruby

Tags:

ruby

a = [1,2,3,4]
b = a << 5
a == [1,2,3,4] # returns false

How to assign b to a with 5 appended to the end without modifying a itself?

like image 223
ThePiercingPrince Avatar asked Mar 05 '26 10:03

ThePiercingPrince


1 Answers

Just sum two arrays:

a = [1,2,3,4]
b = a + [5]

# b == [1, 2, 3, 4, 5]
# a == [1, 2, 3, 4]
like image 138
Yevgeniy Anfilofyev Avatar answered Mar 07 '26 22:03

Yevgeniy Anfilofyev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!