Variables in Ruby, like variables in PHP, don’t have to be given a type when they are declared, but they do have to be given a value before they are used, let’s make a variable that holds a string and display its value.
Giving Values to Variables:
variable="word" puts variable
Variables can be assigned different types at any time. For example we can change the value of a variable from a string to an integer, double or float.
# make string variable variable="word" puts variable # change to integer variable variable=3 puts variable
The result of this code will be
word 3
Like with other languages you can also assign a variable to another variable.
# make string variable variable='word' puts variable # assign an integer variable=3 puts variable # assign a variable to another variable anotherVariable=variable puts anotherVariable
Naming Variables:
Variable names cannot begin with number or symbols except for the underscore “_”
#example _variableName="value"
Constants:
As you know, constants are variables whose value cannot change. All you need to do make a constant is begin a variable name with an uppercase letter.
#example Constant="value"
A constant’s value can change on a different scope, we’ll talk more about how this works when we get to OOP.
Global Variables:
These are variables that are available anywhere in your program. To specify a global variable put a the “$” sign in front of the name.
#example $globalVariable="value"
Instance and Class Variables:
Instance variable begin with the @ sign, class variables begin with two @ signs
# instance variable @instanceVar
# class variable @@classVar
We will cover these two last types of variables when we talk about classes, for now just remember how they are declared.