Since class-level data is accessible throughout the class, it can be initialized at the time the class is defined. If a method named initialize is defined, it is guaranteed to be executed right after an instance is allocated. The initialize is similar to the traditional concept of a constructor, but it does not have to handle memory allocation. Allocation is handled internally by new, and deallocation is handled transparently by the garbage collector.
Showing posts with label object. Show all posts
Showing posts with label object. Show all posts
Wednesday, October 12, 2011
Tuesday, October 11, 2011
Making immutable objects
Mutable objects are objects whose state can change. Immutable objects are objects whose state never changes after creation.
Immutable objects have many desirable properties:
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:
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.
Let us understand what we are doing here - a and b are two variables both of which are pointing to a string object - Original String. We then freeze the object Original String. Hence both a and b are now pointing to the frozen object Original String. This is verified by the statements puts a.frozen? and puts b.frozen?. Next, we create a new string object New String and make variable a point to this new object New String. Variable b is still pointing to the frozen object while a is not. This verified by the last 2 statements of the program.
Usage:
Ruby sometimes copies objects and freezes the copies. When you use a string as a hash key, Ruby actually copies the string, freezes the copy, and uses the copy as the hash key: that way, if the original string changes later on, the hash key isn't affected.
Ruby's internal file operations work from a frozen copy of a filename instead of using the filename directly. If another thread modifies the original filename in the middle of an operation that's supposed to be atomic, there's no problem: Ruby wasn't relying on the original filename anyway. You can adopt this copy-and-freeze pattern in multi-threaded code to prevent a data structure you're working on from being changed by another thread.
Another common programmer-level use of this feature is to freeze a class in order to prevent future modifications to it.
Note: Whenever an object in Ruby has no reference to it, then that object is marked for removal and the garbage collector will remove that object based on its algorithm. There is no way to access an un-referenced object.
Immutable objects have many desirable properties:
- Immutable objects are thread-safe. Threads cannot corrupt what they cannot change.
- Immutable objects make it easier to implement encapsulation. If part of an object's state is stored in an immutable object, then accessor methods can return that object to outside callers, without fear that those callers can change the object's state.
- Immutable objects make good hash keys, since their hash codes cannot change.
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 << 'An attempt to modify.'
- rescue => err
- puts "#{err.class} #{err}"
- end
- # The output is - TypeError can't modify frozen string
- str = 'Original string - '
- str.freeze
- str += 'attachment'
- puts str
- # Output is - Original string - attachment
frozen?
A method frozen? tells you whether an object is frozen or not. Let's take an example here:- a = b = 'Original String'
- b.freeze
- puts a.frozen? # true
- puts b.frozen? # true
- a = 'New String'
- puts a
- puts b
- puts a.frozen? # false
- puts b.frozen? # true
Usage:
Ruby sometimes copies objects and freezes the copies. When you use a string as a hash key, Ruby actually copies the string, freezes the copy, and uses the copy as the hash key: that way, if the original string changes later on, the hash key isn't affected.
Ruby's internal file operations work from a frozen copy of a filename instead of using the filename directly. If another thread modifies the original filename in the middle of an operation that's supposed to be atomic, there's no problem: Ruby wasn't relying on the original filename anyway. You can adopt this copy-and-freeze pattern in multi-threaded code to prevent a data structure you're working on from being changed by another thread.
Another common programmer-level use of this feature is to freeze a class in order to prevent future modifications to it.
Note: Whenever an object in Ruby has no reference to it, then that object is marked for removal and the garbage collector will remove that object based on its algorithm. There is no way to access an un-referenced object.
Variables as reference to objects
Variables are used to hold references to objects. As previously mentioned, variables themselves have no type, nor are they objects themselves; they are simply references to objects.
x = "abc"
An exception to this is that small immutable objects of some built-in classes, such as Fixnum, are copied directly into the variables that refer to them. (These objects are no bigger than pointers, and it is more efficient to deal with them in this way.) In this case assignment makes a copy of the object, and the heap is not used.
Variable assignment causes object references to be shared.
y = "abc"
x = y
x # "abc"
After executing x = y, variables x and y both refer to the same object:
x.object_id # 53732208
y.object_id # 53732208
If the object is mutable, a modification done to one variable will be reflected in the other:
x.gsub!(/a/,"x")
y # "xbc"
Reassigning one of these variables has no effect on the other, however:
# Continuing previous example...
x = "abc"
y # still has value "xbc"
Creating an object in ruby
To create an object from an existing class, the new method is typically used:
myFile = File.new("textfile.txt","w")
myString = String.new("This is a string object")This is not always explicitly required, however. In particular, you would not normally bother to call new for a String object as in the previous example:
yourString = "This is also a string object"
aNumber = 5 # new not needed here, either
Subscribe to:
Posts (Atom)