ruby shift-如何在不移动分配给它的数组的情况下移动数组
我将一个数组分配给另一个数组:ruby shift-如何在不移动分配给它的数组的情况下移动数组,ruby,Ruby,我将一个数组分配给另一个数组: a = ['who','let','the','dogs','out'] b = a b.shift b和a现在都是 ["let", "the", "dogs", "out"]. 我想要一个安静的世界 ["who","let", "the", "dogs", "out"] 你怎么能在不变异a的情况下变异b 还有,为什么会发生这种情况 谢谢 这是因为b和a引用了内存中的同一对象: a = ['who','let','the','dogs','out'] b =
a = ['who','let','the','dogs','out']
b = a
b.shift
b和a现在都是
["let", "the", "dogs", "out"].
我想要一个安静的世界
["who","let", "the", "dogs", "out"]
你怎么能在不变异a的情况下变异b
还有,为什么会发生这种情况
谢谢 这是因为
b
和a
引用了内存中的同一对象:
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"]
当你说:
b = a
您的意思是让b
指向与a
相同的对象。您不是说将a
的内容复制到b
中。为此,您需要使用方法clone
。
除了guitarman的答案之外,还有一种数组方法,它在移位后返回数组的其余部分,而不改变原始数组。只有当您不关心从阵列中移动/放下的内容,并且只关心剩余的项目时,这才有效
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"]
建议使用
.dup
而不是.clone
,以实现这样的简单用法。它们之间的区别非常微妙(.clone
复制单例方法并保持对象的冻结?
状态)——但对于99%的使用,像这样,方法是等效的,但是.dup
稍微快一些。“b引用a”-挑剔,但听起来像是链式变量:b→ A.→ obj
。它实际上更像是a→ obj← b
,即两者引用同一对象,而不是彼此引用。@TomLord和Stefan:你说得对。我更新了我的答案。谢谢