The Ruby Programming Language
class Song # The constructor: def initialize(name, artist, duration) @name = name #instance variables start with @ @artist = artist @duration = duration end #defalt method for turning this instance to a string def to_s "Song: #@name--#@artist (#@duration)" #perl-like replacement, no return. end end # Uses 'new' song = Song.new("Re: Your Brains", "Jonathan Coulton", 272) # Write to stdout puts song #Song: Re: Your Brains--Jonathan Coulton (272) song.name = "new title" # This fails! by default they are private. puts song.name # This also fails. # Subclass Song class KaraokeSong < Song def initialize(name, artist, duration, lyrics) super(name, artist, duration) #call parent constructor @lyrics = lyrics end def to_s super + " [#@lyrics]" end end
4 of 11