How to unfreeze an object in Ruby?

后端 未结 4 1250
生来不讨喜
生来不讨喜 2020-12-13 17:50

In Ruby, there is Object#freeze, which prevents further modifications to the object:

class Kingdom
  attr_accessor :weather_conditions
end

arendelle = Kingd         


        
4条回答
  •  别那么骄傲
    2020-12-13 18:30

    No, according to the documentation for Object#freeze:

    There is no way to unfreeze a frozen object.

    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 introduced String#+@, so you can write +str instead of str.dup if str.frozen?

提交回复
热议问题