class variable vs object variable : instance variables « Class « Ruby






class variable vs object variable


#!/usr/bin/env ruby

class Repeat
  @@total = 0
  def initialize( string, times )
    @string = string
    @times = times
  end
  def repeat
    @@total += @times
    return @string * @times
  end
  def total
    "Total times, so far: " + @@total.to_s
  end
end

data = Repeat.new( "a ", 8 )
ditto = Repeat.new( "A! ", 5 )
ditty = Repeat.new( "R. ", 2 )

puts data.repeat
puts data.total 

puts ditto.repeat
puts ditto.total 

puts ditty.repeat
puts ditty.total

 








Related examples in the same category

1.In Ruby, you prefix instance variables with an at sign @
2.Using a Constructor to Configure Objects
3.Print out the instance variable
4.Adding more accessors