问题描述
我正在学习Ruby,当将Object#freeze
方法与变量一起使用时,我刚刚发现了有趣的行为.
I am learning Ruby, and I just found interesting behaviour when using the Object#freeze
method with variables.
冻结变量(Fixnum
或Array
)之后,我仍然可以对其进行修改!奇怪,因为就我而言,这不应该发生,并且应该提高TypeError
.
After I freeze a variable (either Fixnum
or Array
), I am still able to modify it! It is strange, since as far as I am concerned this should not happen and TypeError
should be raised.
这是我的代码:
test = 666
var = 90
#ok
var += 5
puts "var.frozen? #{var.frozen?}"
var.freeze
puts "var.frozen? #{var.frozen?}"
var = test
puts "var = #{var}"
对于数组也是如此:
test = [666]
var = [90]
#ok
var += [5]
puts "var.frozen? #{var.frozen?}"
var.freeze
puts "var.frozen? #{var.frozen?}"
var = test
puts "var = #{var}"
但是当我尝试在冻结后将某些内容推入数组时,它会产生一个错误,正如预期的那样:
But when I try to push something into the array after freezing, it raises an arror, as expected:
test = [666]
var = [90]
#ok
var += [5]
puts "var.frozen? #{var.frozen?}"
var.freeze
puts "var.frozen? #{var.frozen?}"
var << test
puts "var = #{var}"
有人可以向我解释这个问题吗?看起来很奇怪.
Can somebody explain to me this issue? It seems strange.
编辑我正在使用Windows XP + Ruby 1.9.3-p429
Edit I am using Windows XP + Ruby 1.9.3-p429
推荐答案
您冻结对象,而不是变量,即,您无法更新冻结的对象,但可以将新对象分配给相同的变量.考虑一下:
You freeze objects, not variables, i.e. you can't update a frozen object but you can assign a new object to the same variable. Consider this:
a = [1,2,3]
a.freeze
a << 4
# RuntimeError: can't modify frozen Array
# `b` and `a` references the same frozen object
b = a
b << 4
# RuntimeError: can't modify frozen Array
# You can replace the object referenced by `a` with an unfrozen one
a = [4, 5, 6]
a << 7
# => [4, 5, 6, 7]
顺便说一句:冻结Fixnum
完全是没有用的,因为它们是不可变的对象.
As an aside: it is quite useless to freeze Fixnum
s, since they are immutable objects.
这篇关于冻结Ruby中的变量不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!