1

I'm reading the book Programming Ruby but cannot understand what a class variable @@var is. Can anyone give me some explanation? The book does not talk anything but just mentioned it.

OneZero
  • 11,556
  • 15
  • 55
  • 92
  • please check this http://stackoverflow.com/questions/2084490/ruby-class-variables – HungryCoder Mar 19 '13 at 05:14
  • Check out [John Nunemaker's blogpost on Class and Instance Variables In Ruby](http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/) for a very good explanation. – Prakash Murthy Mar 19 '13 at 05:15
  • I'm talking about class variables @@var instead of instant variables @var. – OneZero Mar 19 '13 at 05:15

1 Answers1

3

A class variable is like an instance variable (@some_var), but its value is global to the class, and any instances of the class.

An example

class Test
  @@test_var = 0
  def show_test
    puts @@test_var
    @@test_var += 1
  end
end

a = Test.new
b = Test.new

a.show_test # prints 0
b.show_test # prints 1
benj
  • 417
  • 1
  • 4
  • 8