+= 运算符似乎修改冻结的字符串 [英] += operator appears to modify frozen string

查看:37
本文介绍了+= 运算符似乎修改冻结的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ruby​​ 冻结方法.就冻结的定义而言,它冻结了调用它的对象的值.我们不能在它之后修改那个对象的值.我必须完成同样的任务,我有一个对象,我正在执行以下代码

I am using ruby freeze method. As far as the definition of freeze is considered, it freezes the value of the object on which it is called. We can not modify the value of that object after it. I have to achieve same task, I have a an object and I am executing following code

a = "Test"
a.freeze
a += "this string"
puts a

输出如下:

Test this string
[Finished in 0.0s]

为什么它会修改我的冻结字符串?

Why it is modifying my frozen string?

推荐答案

没有什么可以修改您冻结的 String

Nothing is modifying your frozen String

您正在使用

a += "this string"

它在 Ruby 中与内部相同

which is internally the same in Ruby as

a = a + "this string"

当您在 Ruby 中添加两个 String 对象时,它将创建一个包含结果的新 String(对于大多数支持它的对象,这是 + 运算符的正常行为).这使原始的测试"和此字符串"值保持不变.原始的、冻结的字符串(包含Test")将保留在内存中,直到它被垃圾收集.可以收集它,因为您已经丢失了对它的所有引用.

When you add two String objects in Ruby, it will create a new String containing the result (this is normal behaviour for + operator on most objects that support it). That leaves the original "Test" and "this string" values unchanged. The original, frozen String (containing "Test") will remain in memory until it is garbage collected. It can be collected because you have lost all references to it.

如果您尝试像这样就地修改对象:

If you attempted to modify the object in place like this:

a << "this string"

那么你应该会看到一个错误信息 RuntimeError: can't modify freeze String

then you should see an error message RuntimeError: can't modify frozen String

基本上,您混淆了局部变量 a 和它所指向的 String 对象.局部变量可以随时重新分配,独立于 Ruby 存储的对象.您可以通过在 a +=... 行之前和之后检查 a.object_id 来验证这是在您的情况下发生的情况.

Basically, you have confused a, the local variable, with the String object to which it is pointing. Local variables can be re-assigned at any time, independently of the objects stored by Ruby. You can verify this is what has happened in your case by inspecting a.object_id before and after your a +=... line.

这篇关于+= 运算符似乎修改冻结的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆