Setter with = : getter setter « Class « Ruby






Setter with =


class Song
  include Comparable
  @@plays = 0
  attr_reader :name, :artist, :duration
  attr_writer :duration
  def initialize(name, artist, duration)
    @name     = name
    @artist   = artist
    @duration = duration
    @plays    = 0
  end
  def to_s
    "Song: #@name--#@artist (#@duration)"
  end
  def duration=(new_duration)
    @duration = new_duration
  end
  def inspect
    self.to_s
  end
end
song = Song.new("Bicylops", "Fleck", 260)
song.duration
song.duration = 257   # set attribute with updated value
song.duration

 








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.Make an attribute readable and writable by using attr_reader, attr_writer
7.Provide the getter
8.Setter with calculation