| Start |
|---|
| Class Variables Class variables have a class wide scope, they can be declared anywhere in the class. A variable will be considered a class variable when prefixed with Class variables are shared between related classes and can be overwritten from a child class This behaviour is unwanted most of the time and can be circumvented by using class-level instance variables. Class variables defined inside a module will not overwrite their including classes class variables: |
| Local Variables Local variables (unlike the other variable classes) do not have any prefix Its scope is dependent on where it has been declared, it can not be used outside the "declaration containers" scope. For example, if a local variable is declared in a method, it can only be used inside that method. Of course, local variables are not limited to methods, as a rule of thumb you could say that, as soon as you declare a variable inside a However, local variables declared in While local variables can not be used outside of its block of declaration, it will be passed down to blocks: But not to method / class / module definitions The variables used for block arguments are (of course) local to the block, but will overshadow previously defined variables, without overwriting them. |
| Global Variables Global variables have a global scope and hence, can be used everywhere. Their scope is not dependent on where they are defined. A variable will be considered global, when prefixed with a Since a global variable can be defined everywhere and will be visible everywhere, calling an "undefined" global variable will return nil instead of raising an error. Although global variables are easy to use its usage is strongly discouraged in favour of constants. |
| Instance Variables Instance variables have an object wide scope, they can be declared anywhere in the object, however an instance variable declared on class level, will only be visible in the class object. A variable will be considered an instance variable when prefixed with The instance variable declared on class level can not be accessed on object level: However, we used the instance variable Instance variables can be declared anywhere in the object, even inside a block: Instance variables are not shared between instances of the same class This can be used to create class level variables, that will not be overwritten by a child-class, since classes are also objects in Ruby. Syntax
RemarksClass variables are shared in the class hierarchy. This can result in surprising behavior. Classes are objects, so instance variables can be used to provide state that is specific to each class. |
Read Article
https://develop.horje.com/learn/1434/reference