Ruby has 5 variable scopes:
- Local Variables: these are the normal variables, example
x = 25
,y = gaurish
wherex
andy
are local variables. - Instance Variables: these are denoted with
@
symbol infront of the actual variable name. mainly used with classes, so that each instance/object of the class has a different/separate value. example.@employee.name = 'Alex'
- Class Variables: denoted with
@@
symbols in front of variable name. class variable, I think have same value accos all instances/object. - Global variables: they start with
$
symbol and are accessible everywhere. example$LOAD_PATH
- Constants: Must start with Capital letter but by convention written in
ALL_CAPS
. although, it is a constant but its value its not constant and can be changed(ruby will throw a warning, though). so in the sense, this also acts like a variable.
As you may notice,all of the above are variables which store some value of some type and their value can be changed. But, each scope does something little bit different. Having 5 different types of variable scopes is confuses hell out of me. Mainly, I have difficulty deciding under what case, I should be using a particular scope in my code. so I have some questions in my mind. please answer:
- I notice that local variables and class variables stay same for all objects/instances, unlike instance variables. so what difference between Local variables and Class variables?
- Can local variables be used in place of class variables? or vice-versa. And if yes, then why, and if no, then why not?
- Global variables in ruby remind me of the evil
global $x
variables in PHP. Are global variables in ruby also considered evil and therefore should not be used. OR, there are specific cases where it makes sense to use global variables in ruby? - Why constants are not constants and allow their value to be changed? A constant's value by definition should be constant right? else, we can just use another variable and don't change its value. would that be equivalent to a CONSTANT in ruby?
- Any page/resource/link which explains the difference between 5 different variable scopes in ruby? I like to keep one handy for reference.
- Under what use-case, I should be using a particular variable scope in my code. so one would explain all 5 cases with can example that would be cool, this is my main reason for confusion.
- is there a de facto choice like
public
in java? Which would be the safe bet in most use-cases?
Thanks for taking time to read and answer question
Person
object might have two instance variables@first_name
and@last_name
, it might also have a local variablex
butx
is unrelated to the state of thePerson
object – Hunter McMillen