What is attr_accessor in Ruby?

5

I'm learning Ruby on Rails and in the content I'm studying I could not fully understand what attr_accessor is and how it works.     

asked by anonymous 13.05.2015 / 14:13

1 answer

8

The attr_accessor is a "shortcut" that creates read, write, and instance variable methods in a class.

link

Ex:

Suppose you have a class Carro wanted to access a property cor :

class Carro
end

carro = Carro.new
carro.cor # => NoMethodError: undefined method 'cor'
carro.cor = 'azul' # => NoMethodError: private method 'cor='

You could implement this way:

class Carro
   @cor=nil

   def cor
      @cor
   end

   def cor=(value)
     @cor = value
   end

end

In this way,

carro = Carro.new
carro.cor = 'azul'
carro.cor # => "azul"

Using attr_accessor , this code is created for you, the class would look like this:

class Carro
   attr_accessor :cor
end

and the functionality is the same.

    
13.05.2015 / 15:30