Anu
Joined: 01 Jan 2010 Posts: 82
|
Posted: Wed Jan 06, 2010 7:27 am Post subject: Mutable and Immutable Objects |
|
|
---------------------------------------------------------------------
Purpose of Using Mutable objects and Immutable objects
----------------------------------------------------------------------
Mutable objects :
-----------------
1)Mutable objects are objects whose state can change.
2)In Ruby, Mutability is a property of an instance.
3)Any instance can become immutable by calling the "freeze".
Immutable objects :
-------------------
1)Immutable objects are objects whose state never changes after creation.
2)Immutable objects are thread-safe(A piece of code is called as thread-safe ,if it functions correctly during simultaneous execution by multiple threads).
Freezing Objects:
1:The freeze method in class Object prevents you from changing an object, effectively turning an object into a constant.
2:After we freeze an object, an attempt to modify the freezed object, results in TypeError.
3: freeze operates on an object reference, not on a variable.
4:This means that any operation resulting in a new object.
Example:
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
Thanks,
Anasuya.N |
|