[Ruby] What is Ruby’s attr_accessor

less than 1 minute read

class Example
   attr_accessor :a, :b
   def initialize(a,b)
     @a = a
     @b = b
   end
end

@ex = Example.new("A", "B")
@ex.a # => "A"

attr_accessor is a method that defines the setter and getter methods for instance variables that match the argument symbol. In this case, “a” is a getter and “=a” is a setter. In other words, attr_accessor :a made the method “a”,”=a”.

@ex.methods.grep /a/ # => [:a.:a=,...]