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

时间:2009-09-23 12:05:11

标签: ruby

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

例如:

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

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

3 个答案:

答案 0 :(得分:93)

至于复制,你可以这样做:

phrase2 = phrase1.dup

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

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

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

答案 1 :(得分:17)

使用您的示例,而不是:

phrase2 = phrase1

尝试:

phrase2 = phrase1.dup

答案 2 :(得分:2)

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"