ruby - 将克隆对象的所有责任转移给库的用户是否正确?

标签 ruby pass-by-reference cloning

我对这件事不是很了解所以我决定在这里问一下。假设我们在 Ruby(或任何其他通过引用传递的脚本语言)中有一些“库”:

class Moo
    attr_accessor :bar
    def initialize
        self
    end
end

a = 'a string'
b = Moo.new
b.bar = a

b.bar 显然与 a 是同一个对象。

所有情况中保留它是否正确,以便需要它们分开的程序员将手动进行克隆?这是我最后得出的唯一明智的想法。

最佳答案

正在关注 the principle of least surprise , 像您所做的那样维护对分配对象的引用是正确的。

如果您在内部做了 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 完全没有必要,因为它与默认的 initialize 相同。

关于ruby - 将克隆对象的所有责任转移给库的用户是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2875693/

相关文章:

c++ - 在 C++ 中使用按引用传递的意外输出

java - 流上的 reduce() 操作似乎正在修改数据源(列表)Stream API Java 8

C# 传递参数(值或引用)?

ruby - 错误 : symbol `pread64' is already defined

ruby-on-rails - 为什么 Rails 菜鸟不应该使用 Gem Devise?

java - 无法克隆数据

javascript - 如果其他选择发生变化,则删除并添加选择框选项

c# - 克隆一个我无法添加 ICloneable 的对象

ruby - 您如何指定适用于英语以外的欧洲语言的正则表达式字符范围?

mysql - 使用 MySQL 而不是 SQLite 创建一个新的 Ruby on Rails 应用程序