CSC/ECE 517 Fall 2012/ch1b 1w56 ms

From Expertiza_Wiki
Jump to navigation Jump to search

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:


attr_accessor :balance


This is equivalent to



def balance
@balance
end

def balance= (bal)
@balance = bal
end


We can also generate getter and setter methods for more than one instance variable.



attr_accessor :balance, :new_balance


We can also use attr_reader if we only want to generate the getter function. Similarly we can use the method call attr_writer for generating just the setter function.

Instance Methods

Instance methods work with instances of the class. So in order to use instance methods we have to create an instance.

Example:


def deposit
@balance += amount
end


You can include the definition of an instance method within the class like this: Example:


Class SavingsAccount < Account
def deposit
@balance += amount
end
end


Or you can also define it later. Since Ruby is a dynamic programming language we are allowed to reopen a class and add methods to it. For instance to add the deposit method after closing the class:


Class SavingsAccount < Account
end
SAcc = SavingsAccount.new
def SAcc.deposit
@balance += amount
end


The save and update methods used in Rails are actually instance methods.