programming.nbk: Home | Index | Next Page: Ruby: Classes | Previous Page: Ruby: case
Class definition:
class Song def initialize(name, artist, duration) @name = name @artist = artist @duration = duration end end
The initialize method is called after a new instance of a class is created:
aSong = Song.new("Bicylops", "Fleck", 260)
You can add to a class subsequent to it's definition:
class Song def to_s "Song: #{@name}--#{@artist} (#{@duration})" end end aSong = Song.new("Bicylops", "Fleck", 260) aSong.to_s » "Song: Bicylops--Fleck (260)"
A class can be created based on another class using inheritance:
class KaraokeSong < Song def initialize(name, artist, duration, lyrics) super(name, artist, duration) @lyrics = lyrics end end
Ruby only supports single-inheritance.
In the above example, KaraokeSong is a subclass of Song, and Song is the superclass of KaraokeSong.
In the above example, super causes the same method of the object's parent object to be called. In this case, the parents initialize method is called.
A class instance's instance variables are private, they can not be accessed by code external to the class. Ruby provides a shortcut to create accessor methods:
class Song attr_reader :name, :artist, :duration end
This generates code equivalent to:
class Song def name @name end def artist @artist end def duration @duration end end
Ruby provides a shortcut to create attribute setters:
class Song attr_writer :duration end
This generates code equivalent to:
class Song def duration=(newDuration) @duration = newDuration end end
programming.nbk: Home | Index | Next Page: Ruby: Classes | Previous Page: Ruby: case
Notebook exported on Monday, 7 July 2008, 18:56:06 PM Eastern Daylight Time