Search code examples
rubyclass-variables

Class variables in Ruby


I've come across the following example from this tutorial:

class Song
  @@plays = 0

  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
    @plays = 0
  end

  def play
    @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)   

puts s1.play
puts s2.play
puts s1.play
puts s1.play 

Is @@plays politely accessible only inside the class Song? This commentary brings up the point of not recommending the use of class variables. Is it b/c they are often not required in common-day use, and create a lot of debugging headaches when used?


Solution

  • The @@ variable will a class variable. This is generally bad practice. In your code its redundant because @plays == @@plays (unless you set @@plays elsewhere in your code (bad practice))

    Actually now that I look at it, they aren't really the same. @plays keeps a count of how many times an individual song has been played, and @@plays will keep a count of all songs. Still, its likely bad practice to use @@plays. Usually, you'd have a parent class like "Player" that is managing all the songs. There should be an instance variable called @total_plays in the "Player" class.