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.
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.
The attr_accessor
is a "shortcut" that creates read, write, and instance variable methods in a class.
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.