如何在 Ruby 中解冻对象? [英] How to unfreeze an object in Ruby?

查看:45
本文介绍了如何在 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?

这篇关于如何在 Ruby 中解冻对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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