如何在 Ruby 中解冻对象?
在 Ruby 中,有 Object#冻结
,防止进一步修改对象:
In Ruby, there is Object#freeze
, which prevents further modifications to the object:
class Kingdom
attr_accessor :weather_conditions
end
arendelle = Kingdom.new
arendelle.frozen? # => false
arendelle.weather_conditions = 'in deep, deep, deep, deep snow'
arendelle.freeze
arendelle.frozen? # => true
arendelle.weather_conditions = 'sun is shining'
# !> RuntimeError: can't modify frozen Kingdom
script = 'Do you want to build a snowman?'.freeze
script[/snowman/] = 'castle of ice'
# !> RuntimeError: can't modify frozen String
但是,没有Object#unfreeze
.有没有办法解冻一个冰冻的王国?
However, there is no Object#unfreeze
. Is there a way to unfreeze a frozen kingdom?
否,根据 Object#freeze
的文档:
No, according to the documentation for Object#freeze
:
无法解冻冻结的对象.
冻结状态存储在对象内.调用 freeze
设置冻结状态,从而防止进一步修改.这包括对对象冻结状态的修改.
The frozen state is stored within the object. Calling freeze
sets the frozen state and thereby prevents further modification. This includes modifications to the object's frozen state.
关于您的示例,您可以改为分配一个新字符串:
Regarding your example, you could assign a new string instead:
script = 'Do you want to build a snowman?'
script.freeze
script = script.dup if script.frozen?
script[/snowman/] = 'castle of ice'
script #=> "Do you want to build a castle of ice?"
Ruby 2.3 引入了String#+@
,所以你可以写 +str
而不是 str.dup if str.frozen?
Ruby 2.3 introduced String#+@
, so you can write +str
instead of str.dup if str.frozen?