coding, ruby

Dot Freeze – fairly easy to prevent objects from modification

Freeze and Frozen?

Too bad NodeJS doesn’t have this feature but Ruby does!

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.

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

Share This:

Leave a Reply