Instance Variables
We cover instance variables briefly in The RubyMonk Ruby Primer: Building your own class lesson.
There really isn't much more to instance variables. They are bound to an instance of a class and together forms what we call the state of an object. Every instance of a class has a different set of instance variables. Let us see how that works out:
As you can see from the above example, Item.new
creates a new object - an instance of the class Item
. The instance variables, in the example above, @item_name
and @quantity
, are prefixed by the @
symbol. This is enforced by Ruby - if your variable does not start with a @
, it is considered to be a local variable.
What is the difference between local and instance variables? I'll demonstrate by an example. Note that the following example is going to raise an error and that is fine.
The error message should be instructive on how the local variable supplier
operates. A local variable is available only inside the method it is defined. It is not shared across the entire object. In programming language parlance, we say that the 'scope' of a local variable is bound to the method where it is defined.
Contrast the scope of a local variable with that of an instance variable: the instance variable is bound to the specific instance of the class. By binding itself to the entire object, an instance variable makes itself available to every method of the object.