Ruby:如何在不指向同一对象的情况下复制变量?


73

在Ruby中,如何复制变量以使对原始变量的更改不会影响复制?

例如:

phrase1 = "Hello Jim"
phrase2 = phrase1
phrase1.gsub!("Hello","Hi")
p phrase2 #outputs "Hi Jim" - I want it to remain "Hello Jim"

在这个例子中,两个变量指向同一个对象。我想为第二个变量创建一个新对象,但最初要包含相同的信息。

Answers:


106

至于复制,您可以执行以下操作:

phrase2 = phrase1.dup

要么

# Clone: copies singleton methods as well
phrase2 = phrase1.clone

您也可以这样做,避免完全复制:

phrase2 = phrase1.gsub("Hello","Hi")


3
phrase1 = "Hello Jim"
   # => "Hello Jim"

phrase2 = Marshal.load(Marshal.dump(phrase1))
   # => "Hello Jim"

phrase1.gsub!("Hello","Hi")
   #  => "Hi Jim" 

puts phrase2
   # "Hello Jim"

puts phrase1
   # "Hi Jim"

7
回答时,请说明您的解决方案为何有帮助。这样可以使询问的人受到启发,以便他们将来可以理解并避免该问题。
Tin Man
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.