static variables in ruby

Class variables are shared between all instances (which is why they’re called class variables), so they will do what you want. They’re also inherited which sometimes leads to rather confusing behavior, but I don’t think that will be a problem here. Here’s an example of a class that uses a class variable to count how many instances of it have been created:

class Foo
  @@foos = 0

  def initialize
    @@foos += 1
  end

  def self.number_of_foos
    @@foos
  end
end

Foo.new
Foo.new
Foo.number_of_foos #=> 2

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)