按照最不意外的原则,保持对已分配对象的引用是正确的。
如果您在内部dup
执行分配给 的对象,那么对于想要引用相同对象的库使用者来说bar
,这将是非常令人沮丧的。 bar
> class Moo
> attr_accessor :bar
> end
=> nil
> a = 'a string'
=> "a string"
> b = Moo.new
=> #<Moo:0x2bfd238>
> b.bar = a
=> "a string"
> a.upcase!
=> "A STRING"
> b.bar # should be uppercase as expected since `a` was modified *in-place*
=> "A STRING"
> b.bar = a.dup # now modifications to `a` will not affect `bar`
=> "A STRING"
> a.downcase!
=> "a string"
> b.bar
=> "A STRING"
作为旁注,def initialize() self end
完全没有必要,因为它与 default 相同initialize
。