Provide the getter : getter setter « Class « Ruby






Provide the getter


class CD
  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
    "CD: #@name--#@artist (#@duration)"
  end
  def name
    @name
  end
  def artist
    @artist
  end
  def duration
    @duration
  end
end

d = CD.new("B", "F", 260)
d.artist
d.name
d.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.Setter with calculation
8.Setter with =