Freezing Objects
The freeze method in class Object prevents you from changing an object, effectively turning an object into a constant. After we freeze an object, an attempt to modify it results in TypeError. The following program illustrates this:
str = 'A simple string. ' str.freeze begin str << 'An attempt to modify.' rescue => err puts "#{err.class} #{err}" end # The output is - TypeError can't modify frozen string
|
However,
freeze operates on an object reference, not on a variable. This means that any operation resulting in a new object will work. This is illustrated by the following example:
str = 'Original string - ' str.freeze str += 'attachment' puts str # Output is - Original string - attachment |
The expression str + 'attachment' is evaluated to a new object, which is then assigned to str. The object is not changed, but the variable str now refers to a new object. A method
frozen? tells you whether an object is frozen or not.