attr_reader, attr_writer, attr_accessor

curtains

 

In the last post I said I was writing out getter and setter methods the long way, so today I am going to write out the short way!

Here is a class called Movies:


class Movies

def initialize(name, location)
@name = name
@location = location
end

end

  • We have our instance variables all set up! The next thing we want to do is make them accessible outside of the class.
  • What if we ONLY want to be able to read these instance variables, but don’t want to let anyone change their values?
  • You would use attr_reader accessor. The ‘attr’ stands for attribute.

class Movies

attr_reader :name, :location

def initialize(name, location)
@name = name
@location = location
end

end

  • That’s it! Instead of writing out the getter method which would look like this:

class Movies

def initialize(name, location)
@name = name
@location = location
end

def name
@name
end

def location
@location
end 

end

  • This would save us a lot of time if this class had a lot of instance variables that we would want to access. What if we wanted to ONLY be able to change the value of our instance variables? We would use the attr_writer accessor!

class Movies

attr_writer :name, :location

def initialize(name, location)
@name = name
@location = location
end

end

  • This is great if we only want to just read or write to the instance variable, but what if we wanted to do both? It would be a lot of writing if we had to attr_reader and attr_writer for all our instance variables. This is when you would use attr_accessor. This will let you be able to both read or write with your instance variable.

class Movies

attr_accessor :name, :location

def initialize(name, location)
@name = name
@location = location
end

end

  • The code above is equivalent to the following code:
class Movies 

 def initialize(name, location)
 @name = name
 @location = location
 end 

 def name=(name) #this is the setter method
 @name = name
 end

 def name #this is the getter method
 @name
 end

 def location=(location) #this is the setter method
 @location = location
 end

 def location #this is the getter method
 @location
 end

end
  • So rather than writing all these methods out every time you would like to access your instance variables you can now use these attribute accessors!