ruby shift - 如何在不移动分配给它的数组的情况下移动数组

时间:2017-06-14 12:13:56

标签: ruby

我将一个数组分配给另一个:

a = ['who','let','the','dogs','out']
b = a
b.shift

b和a现在两者都是

["let", "the", "dogs", "out"].

我想要一个仍然是

["who","let", "the", "dogs", "out"]

如何在不改变?的情况下改变b?

另外,为什么会这样?

谢谢!

2 个答案:

答案 0 :(得分:7)

那是因为ba引用了内存中的同一个对象:

a = ['who','let','the','dogs','out']
b = a
a.object_id == b.object_id
# => true

b需要是另一个数组对象,所以我要创建一个a的克隆:

a = ['who','let','the','dogs','out']
b = a.dup
a.object_id == b.object_id
# => false

b.shift
# => "who"
b
# => ["let", "the", "dogs", "out"]
a
# => ["who", "let", "the", "dogs", "out"]

答案 1 :(得分:1)

当你说:

b = a

您说让b指向与a相同的对象。您并不是说将a的内容复制到b。为此,您需要使用方法clone。 除了吉他手的答案之外,还有一种数组方法,可以在移位后返回数组的其余部分,而无需更改原始数组。这只适用于你不关心你正在转移/放弃阵列的东西而只关心剩余的物品。

1 > a = ['who','let','the','dogs','out']
 => ["who", "let", "the", "dogs", "out"] 
2 > b = a.drop(1)
 => ["let", "the", "dogs", "out"] 
3 > a
 => ["who", "let", "the", "dogs", "out"] 
4 > b
 => ["let", "the", "dogs", "out"]