CSC/ECE 517 Fall 2012/ch1b 1w56 ms
Introduction
-Content-
Object
Content
Class
Content
Inheritance
Content
Instance Variables and Accessor Methods
Instance Variables
An instance variable begins with the symbol “@” in Ruby. It is different from a local variable because its scope is confined to the object to which self refers. Instance variables are invisible outside of the object. The only way we can access them or observer them is by writing methods to get or set the value of them. Instance variables have the value “nil” until they are initialized.
Instance variables do not need to be declared. In fact we can also access instance variables without declaring or initializing it, this will not raise an exception. However a warning will be issued if we run it using the –w switch.
Every instance variable is dynamically appended to an object in the first assignment.
Example:
@balance -> instance variable
Accessor Methods
As stated previously, we cannot access instance variables from anywhere outside an object. Hence we need to define methods to access them. They are generally called as getter and setter methods.
The getter method is used to return the value of the instance variable. It would be defined as:
Example:
def balance
@balance
end
The setter method is used to set the value of the instance variable. Setter methods always end with the “=” sign. It would be defined as:
Example:
def balance= (bal)
@balance = bal
end
Instead of writing getter and setter methods for each class, we can use the attr_accessor function. The attr_accessor is a method call which uses metaprogramming to generate the getter and setter methods dynamically at run time.
Example: