2013-07-14 71 views

回答

6

紅寶石變量持有引用對象和=操作複製引用

看來你想clonea

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] 
+4

也許['dup' ](http://www.ruby-doc.org/core-2.0/Object.html#method-i-dup),取決於OP想要什麼。另請參見[Ruby的'dup'和'clone'方法有什麼區別?](http://stackoverflow.com/questions/10183370/whats-the-differences-between-ruby-dup-and-clone-method) –

+0

@AndrewMarshall:好的,謝謝! – Johnsyweb

9

算了筆兩個數組:

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

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

我通常做這種方式:

b = [*a, 5] 
+2

或更簡單:'b = * a,5' –

+0

這樣比較好。 – sawa