#Ruby Class 2: Why Attribute Accessor?

In class 1 we defined the instance variables and we saw how difficult to accessing it. We managed to access it via calling methods that initializing it.
So we can simplify it by defining access methods.

class Test
 def initialize
  @one = 1
 end 
 def get_one
   @one
 end 
end

The ‘get_one’ method is the reader method for reading the instance variable value.

Ruby has shortcut for this.

class Test
 attr_reader :one
 def initialize
  @one = 1
 end 
 
end

These accessor methods are identical to the methods we wrote by hand earlier.

Sometimes we need to modify the value of these variables from outside. how we do that?

At first we can do this by hand:

class Test
 def initialize
  @one = 1
 end 
 def one=(new_value)
   @one = new_value
 end 
end

The above code allows us to call ‘equal to’ sign on the objects method. This is the setter method. We can set a value to @one like:

t = Test.new
t.one = 3
t.one
=> 3

Ruby also provides a shortcut for this. It is: ‘attr_writer’, so rewrite the above code:

class Test
 attr_writer :one
 def initialize
  @one = 1
 end 
end

Most of the cases we needed ‘attr_reader’ and ‘attr_writer’. So the code becomes:

class Test
 attr_reader :one
 attr_writer :one

 def initialize
  @one = 1
 end 
end

We can again simplify the above code!

class Test
 attr_accessor :one

 def initialize
  @one = 1
 end 
end

How is it? Nice. is n’t it?

Advertisements

Author: Abhilash

Hi, this is Abhilash - Senior Programmer Analyst at CoMakeIT, specialised on web programming. Mainly working on Ruby On Rails platform since 2010.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s