2
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?

ThePiercingPrince
  • 1,873
  • 13
  • 21

3 Answers3

9

Just sum two arrays:

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

# b == [1, 2, 3, 4, 5]
# a == [1, 2, 3, 4]
Yevgeniy Anfilofyev
  • 4,827
  • 25
  • 27
6

Ruby variables hold references to objects and the = operator copies the references.

It seems you wish to clone a:

irb(main):001:0> a = [1,2,3,4]
=> [1, 2, 3, 4]
irb(main):002:0> b = a.clone << 5
=> [1, 2, 3, 4, 5]
irb(main):003:0> a
=> [1, 2, 3, 4]
irb(main):004:0> b
=> [1, 2, 3, 4, 5]
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
  • 4
    Or maybe [`dup`](http://www.ruby-doc.org/core-2.0/Object.html#method-i-dup), depending on what the OP wants. See also [What's the difference between Ruby's `dup` and `clone` methods?](http://stackoverflow.com/questions/10183370/whats-the-differences-between-ruby-dup-and-clone-method) – Andrew Marshall Jul 14 '13 at 16:26
5

I usually do it this way:

b = [*a, 5]
sawa
  • 165,429
  • 45
  • 277
  • 381