A Constant Variable
Riddle: What’s nowhere but everywhere except where something is?
Quick blog to illustrate the power/use of my newfound favourite Ruby variable — the instance variable. Defined with an
@ in front of the variable name.
For instance (pun intended):
@variable = "instance variable"
variable = "local variable"
For people new to Ruby / coding, you will be minding your business, having fun, writing methods, puts’ing “Hello World” and gets.chomp’ing responses when all of a sudden, things get complicated.
You set a value for a variable in one place / method, find you want to use it in another method, but the programme isn’t having it:
Then with a magic
To successfully access / use the instance variable in different methods, note that either:
- it must be initialised outside of a method first (as per above example)
2. if the variable is an output of / defined in a method_A, give method_A as an argument to the method_B you’d like to use it in:
This is as opposed to calling the instance variable directly into method_B, which won’t work:
(2) can get complicated if the method does more than just return an object. So shovelling values
<< and using (1) comes in handy for adding to and accessing the variable from multiple methods:
Answer to riddle: Nothing