正在看《The Ruby Programming Language》,书中说到 clone 是浅拷贝,于是做了如下测试
irb(main):007:0> class Klass
irb(main):008:1> attr_accessor :str
irb(main):009:1> end
=> nil
irb(main):010:0> s1 = Klass.new
=> #<Klass:0x7f301a290d50>
irb(main):011:0> s1.str = "Hello"
=> "Hello"
irb(main):012:0> s2 = s1.clone
=> #<Klass:0x7f301a281e90 @str="Hello">
irb(main):013:0> s1
=> #<Klass:0x7f301a290d50 @str="Hello">
irb(main):014:0> s2
=> #<Klass:0x7f301a281e90 @str="Hello">
irb(main):015:0> s2.str[1,4] = "i"
=> "i"
irb(main):016:0> s1
=> #<Klass:0x7f301a290d50 @str="Hi">
irb(main):017:0> s2
=> #<Klass:0x7f301a281e90 @str="Hi">
以上 s1 的内容随着 s2 的改变而改变,说明 clone 是一个浅拷贝
irb(main):018:0> a = Array.new
=> []
irb(main):019:0> a.push(1).push(2).push(3)
=> [1, 2, 3]
irb(main):020:0> a
=> [1, 2, 3]
irb(main):021:0> b = a.clone
=> [1, 2, 3]
irb(main):022:0> a
=> [1, 2, 3]
irb(main):023:0> b
=> [1, 2, 3]
irb(main):024:0> b.push(4)
=> [1, 2, 3, 4]
irb(main):025:0> a
=> [1, 2, 3]
问题:为什么这里 a,b 两个数组的内容不一样?