需要使我的程序中的某些 Ruby 字符串不可变。什么是最好的解决方案?在 String
类上编写包装器?
freeze
方法对我不起作用。我看到 freeze
不允许您解冻对象。
以下是我的情况:我有一个将字符串传递给回调的类。该字符串恰好是该类的一个实例变量,并且可能很大。不想callback去修改,还是让class随意修改。
最佳答案
Following is my situation: I have a class that passes a string to a callback.
将字符串的副本传递给回调有效吗?
This string happens to be an instance variable of the class and can be potentially large. I don't want the callback to modify it, but still allow the class to modify it at will.
如果您担心字符串的大小,那么使用 String#dup 会有所帮助。它将创建一个新对象,具有不同的 object_id
,但不会复制字符串的内容,除非新字符串(或原始字符串)被修改。这称为“写时复制”,并在 Seeing double: how Ruby shares string values 中进行了描述。 .
关于ruby - 使 Ruby 字符串不可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11148276/