Mega Code Archive

 
Categories / Ruby / Class
 

Update both instance variable and class variable

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 play     @plays  += 1   # same as @plays = @plays + 1     @@plays += 1     "This  song: #@plays plays. Total #@@plays plays."   end end s1 = Song.new("Song1", "Artist1", 234)  # test songs.. s2 = Song.new("Song2", "Artist2", 345) s1.play s2.play s1.play s1.play