Tuesday, 4 February 2014

Ruby - Variables Categories and Scope


In this post I wanted to do a quick separate introduction to Ruby variables 'categories' and 'scope'. 

These are two aspects to be really clear on from the start as not being will create much confusion! I may be teaching you to suck eggs here, but we can;t script well if we don't have this bit nailed.

When working with variables in Ruby, we have a number of options for which category of variable we want to use. Some key points before we look at the different categories:
  • Variables make the data they refer to available differently depending on scope
  • We denote which category of variable it is by using a sigil attached to the variable name
  • We can’t use a number or capital letter at the start of a variable name or it will be a Constant
The choices of variable, with their respective sigils are:
  • Local: no sigil is used for local variables
  • Global: $
  • Instance: @
  • Class: @@
  • Constant: if the variable name starts with a capital letter, it’s a Constant 
We'll cover each in detail in the next few videos, but in summary:

Local variables are limited to the immediate bit of code
Global variables are available to use from anywhere in the script
Instance variables are unique to any instance of an object (such as a Class)
Class variables are common to all instance of a Class

Watch the video for a Walkthrough as per the Whiteboard below!

0 comments: