Ruby:我怎样才能复制一个variables,而不指向同一个对象?
在Ruby中,如何复制一个variables,使原来的变化不影响副本?
例如:
phrase1 = "Hello Jim" phrase2 = phrase1 phrase1.gsub!("Hello","Hi") p phrase2 #outputs "Hi Jim" - I want it to remain "Hello Jim"
在这个例子中,这两个variables指向同一个对象; 我想为第二个variables创build一个新的对象,但最初包含相同的信息。
至于复制你可以这样做:
phrase2 = phrase1.dup
要么
# Clone: copies singleton methods as well phrase2 = phrase1.clone
你也可以这样做,以避免复制:
phrase2 = phrase1.gsub("Hello","Hi")
使用你的例子,而不是:
phrase2 = phrase1
尝试:
phrase2 = phrase1.dup
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"