attr_reader creates one or more instance variables, with corresponding methods that return (get) the values of each method. : attr_reader « Class « Ruby






attr_reader creates one or more instance variables, with corresponding methods that return (get) the values of each method.


# attr_writer method automatically creates one or more instance variables, with corresponding methods that set the values of each method. 

class Dog
  attr_reader :bark
  attr_writer :bark
end

dog = Dog.new

dog.bark="Woof!"
puts dog.bark # => Woof!

dog.instance_variables.sort # => ["@bark"]
Dog.instance_methods.sort - Object.instance_methods # => [ "bark", "bark=" ]

 








Related examples in the same category

1.Calling the attr_accessor method does the same job as calling both attr_reader and attr_writer together, for one or more instance methods
2.Use attr_reader to add a new attribute and use initialize method to set it
3.attr_reader creates these accessor methods for you.