irb(main):001:0> person1 = "Tim"
=> "Tim"
irb(main):002:0> person2 = person1
=> "Tim"
irb(main):003:0> person1[0]='J'
=> "J"
irb(main):004:0> person1
=> "Jim"
irb(main):005:0> person2
=> "Jim"
person1赋值给person2并不会创建任何新对象;只是将person1的对象引用拷贝给person2,person1和person2都指向同一个对象。
irb(main):006:0> person1 = "Tim"
=> "Tim"
irb(main):007:0> person2 = person1.dup
=> "Tim"
irb(main):008:0> person1[0] = 'J'
=> "J"
irb(main):009:0> person1
=> "Jim"
irb(main):010:0> person2
=> "Tim"
使用String的dup方法避免创建别名,它会创建一个新的、具有相同内容的String对象。
irb(main):009:0> person1
=> "Jim"
irb(main):010:0> person2
=> "Tim"
irb(main):011:0> person1 = "Tim"
=> "Tim"
irb(main):012:0> person2 = person1
=> "Tim"
irb(main):013:0> person1.freeze
=> "Tim"
irb(main):014:0> person2[0] = 'J'
RuntimeError: can't modify frozen String
from (irb):14:in `[]='
from (irb):14
from C:/Ruby22-x64/bin/irb:11:in `<main>'
也可以通过冻结一个对象来阻止其他人进行改动。如果更改,则会引发TypeError异常。