Make an attribute readable and writable by using attr_reader, attr_writer : getter setter « Class « Ruby






Make an attribute readable and writable by using attr_reader, attr_writer


#!/usr/bin/env ruby

class Dog
  attr_reader :bark
  attr_writer :bark
end

dog = Dog.new

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

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

 








Related examples in the same category

1.Add a method named get_color, which returns the color of animal objects created from this class:
2.Call a member method
3.getter and setter
4.Accessors
5.Define getter for a attribute
6.Provide the getter
7.Setter with calculation
8.Setter with =