1

I'm trying to figure out the following: what the difference between this

class Car
    @@count = 1
end

and this

class Car
    count = 1
end

I understand that @@ is used to define a class variable, but isn't any variable declared within a class considered a variable within that class' scope?

krabbos
  • 47
  • 4
  • To answer your specific question, no: local variables are lexically scoped, class variables are always accessible in that class. `class Foo; @@klass = 1; local = 2; end; class Foo; puts @@klass; puts local; end` will show you the difference. `@@klass` will print fine (we're still in the same class), `local` will be an error since it is undefined in that code scope. – Amadan Jan 26 '17 at 06:50
  • I think I get it now. The "local" variable is scoped within the exact object it is declared in, for example a certain class or a method etc., while the class variable is an entity of that class. – krabbos Jan 26 '17 at 07:01
  • @krabbos The easiest way to think of it is as if you've wanted to change a functionality of the every instance of the class instantly. Let me give you an example. If you were building an airport system for example, how would you notify the users that all the flights for the given period have been cancelled? Well easy - you create @@cancelled field, and update it when needed, and it reflects to the each object and instance of the class. – mutantkeyboard Jan 26 '17 at 09:13

0 Answers0