tags:

views:

39

answers:

1

I see that Ruby has the following variables: - global variables (represented by $variable_name) - class variables (represented by @@variable_name) - instance variables (represented by @variable_name) and - local variables (represented by variable_name or _variable_name)

Occasionally I see the following in the rails source code:

class SomeClass @var end

Here what exactly @var represent and what do you call it, metaclass variable? Also whats the advantage of using this kind of variables?

+1  A: 

It is one of the classes instance variables. In Ruby, everything is an object, even classes, so it isn't surprising that classes can have instance variables.

class A
  @@class_var = 1
  @instance_var = 1
end
A.class_variables
#=> ["@@class_var"]
A.instance_variables
#=>["@instance_var"]

More Info

BaroqueBobcat
Thats what I thought, but whats the purpose or use case of using classes instance variables? Also are all the instances created from this particular class share these? If yes, how can a instance of a class access these variables? We cannot just say @instance_var, that would try to query for the instances instance variable, we cannot just say @@instance_var, that would try to query for the class variable.
satynos
@instance is only for the current instance of the object (all objects have this variable, but it's value is unique to the instance)@@class is shared across all instances of the objects (all objects have and share this variable, value is not unique)Take a look at attr_accessor :myvariable as a quick way to set up your gets and sets for your variables.
Beanish
You cannot access it because it is a private variable. If you define an accessor like this (def A.get_instance_var @instance_var end) you can access it with (A.new).class.get_instance_var. As for the utility of this ... that's the beauty of metaprogramming, you have no clue something is either possible or usefull until you try it, it works, and it solves some problem ;)
phtrivier
@phtrivier: Thanks for the clarification, that explains a whole lot. Based on your example, I am assuming it behaves more or less like class variables, I mean all the instances of A will get to the same value and if one instance modifies it, it reflects in all the other instances. If that is true, I don't quite see the difference between them and class variables, correct me if I am wrong.
satynos
@BaroqueBobcat: Thanks for the link that clarifies a lot with the use cases. Initially I didn't see that link which is why I posted several comment responses.
satynos