A variable is an identifier or name that can be assigned a value, and a value has, or
will have, a type at runtime (when the program runs). An example is found in the following
statement, where the variable
x is assigned the value
100 by the equals sign.
x = 100
Now the local variable
x holds the value
100. But, hey, what type is it? Looks like an integer to me—how
about you? And what does Ruby think?
Many modern programming languages, like C++ and Java, are statically typed. This basically means that a variable is assigned a type at the time it is declared, and, because these languages are also strongly typed, the variable remains that type unless it is cast into a different type, if it is possible to do so.
For example, in Java, you would declare variables with the types (
int) on the left:
int months = 12; int year = 2007;
Ruby doesn't have type declarations. It just assigns values to variables, like this:
months = 12 year = 2007
You could use a semicolon at the end of the line if you wanted, but a newline character is all you really need.
The values in
year are clearly integers, but
you didn't have to give them a type because Ruby does that for you, automatically. It's
called dynamic or duck typing.
This is how duck typing works: if you observe an aquatically competent bird, and it walks like a duck, quacks like a duck, flies like a duck, and swims like a duck, well, by George, it's probably a duck. Ruby likewise looks at a value assigned to a variable, and if ...