: 
http://rubylearning.com/ http://rubylearning.com/satishtalim/tutorial.html http://rubylearning.com/download/downloads.html http://rubylearning.com/other/certification.html http://rubylearning.com/blog/ http://rubylearning.com/other/ruby_news.html http://rubylearning.com/other/testimonials.html http://rubylearning.com/jobs/ruby_jobs.html http://rubylearning.com/other/ruby_gurus.html http://rubylearning.com/satishtalim/services.html http://rubylearning.com/contact/contact.html http://rubylearning.com/satishtalim/about.html

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.


Learning Ruby Navigation                                                                <Syntactic Sugar  | TOC  |  Object Serialization>