ruby notes(6)

  • Mutable objects are objects whose state can change. Immutable objects are objects whose state never changes after creation. Any instance can become immutable by calling freeze.

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 p050xfreeze.rb illustrates this:

str = ‘A simple string. ‘
str.freeze
begin
str < 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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s