What is attr_accessor in Ruby?

Asked

Viewed 6,657 times

7

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

1 answer

14


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

http://apidock.com/ruby/Module/attr_accessor

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 it 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.

  • For those who are used to other POO languages, yes, attr_accessor is nothing more than a getter / Setter for an object in Ruby! https://www.rubyguides.com/2018/11/attr_accessor/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.