Ruby/Class/Class Variables
Материал из Wiki.crossplatform.ru
Class variable and instance variable with the same name
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 @@plays += 1 "This song: #@plays plays. Total #@@plays plays." end def record "Recording..." end def inspect self.to_s end def <=>(other) self.duration <=> other.duration end end
Creating Class Variables
# create instance variables by prefixing a variable name with @. # create class variables by prefixing a variable"s name with @@. # A class variable is shared by all instances of a class # Only one copy of a class variable exists for a given class. # You have to initialize (declare a value for) a class variable before you use it. class Animal @@number_animals = 0 def initialize(color) @color = color @@number_animals += 1 end def get_color return @color end def get_number_animals return @@number_animals end end dog = Animal.new("brown") cat = Animal.new("striped") squirrel = Animal.new("gray") puts "Number of animals is " + squirrel.get_number_animals.to_s
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