dup 复制只复制 实例 的内容. clone 除了内容, 还可以复制与 实例 有联系的东西, 比如说单例方法.
str = "66" def str.show p "77" end str_clone = str.clone str_dup = str.dup str_clone.show #=> "77" str_dup.show #=> NoMethodError
str = "66"
def str.show
p "77"
end
str_clone = str.clone
str_dup = str.dup
str_clone.show #=> "77"
str_dup.show #=> NoMethodError
不过 dup 和 clone 都是浅复制, 对于一些实例有引用的东西, 就不能很好的复制了.
str = [66, "66"] str_dup = str.dup str_dup[1][0] = "7" str_dup[0] = 77 p str #=> [66, "76"] p str_dup #=> [77, "76"] str = [66, "66"] str_clone = str.clone str_clone[1][0] = "7" str_clone[0] = 77 p str #=> [66, "76"] p str_dup #=> [77, "76"]
str = [66, "66"]
str_dup = str.dup
str_dup[1][0] = "7"
str_dup[0] = 77
p str #=> [66, "76"]
p str_dup #=> [77, "76"]
str = [66, "66"]
str_clone = str.clone
str_clone[1][0] = "7"
str_clone[0] = 77
p str #=> [66, "76"]
p str_dup #=> [77, "76"]
|