#Ruby Class 2: Why Attribute Accessor?

In class 1 we defined the instance variables and know 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?

#Ruby Class 1: Ruby’s instance variable and initialize method simplified

We read so many documents about ruby but do you think about some facts that we really don’t know. See below.

1. Instance variables are accessible across the class for that instance

Example:

class Test2
 def one
  @one = 1
  @two
 end
 def two
  @two = 2
  @one
 end
end

Here

t = Test.new
=> 
t.one is what ?
t.two is what ?

Can you guess?

t.one is nil why? t.one will return @two, but it is not initialized yet. We have to call t.two for intitializing it (the variable gets a value).

t.two is what?
Ans: 1
Why? because we already initialized @one by calling t.one above. If not it will also return nil.

So what is the purpose of instance variable if we are not getting its value when initializing the Class (say t = Test.new)

Here is the importance of ‘initialize’ method. Lets change the method named ‘two’ to ‘initialize’

class Test3
 def one
  @one = 1
  @two
 end
 def initialize
  @two = 2
  @one
 end
end

then you try:

t = Test.new
=>    ### See here already declared the variable @two

t.one
=> 2

Nice. So we can access that instance variable anywhere in the class. How is that? ๐Ÿ™‚