Designed to be more powerful than Perl and more object-oriented than Python, Ruby is a dynamic, reflective, general-purpose programming language that has risen in popularity because of its power and ease of use. In our Ruby Programming training course, expert instructor Mike McMillan states that the first thing any programmer needs to know is how to create variables and constants.
A summary of variables:
Ruby uses very limited punctuation, and prefers English keywords, though some punctuation is needed to decorate Ruby. It uses simple naming conventions to denote the scope of variables:
var could be a local variable
@var is an instance variable
$var is a global variable
Creating Variables and Constants:
Mike focuses his lesson on local variables, explaining that to create a constant you simply need to provide a name and a value using an assignment statement – for example: write number = 100, now the variable number holds the value 100. If you type the variables name, it retrieves the value that’s been stored in that variable. There are some general rules to naming variables. To start with, a variable name must begin with a lower case letter or an underscore. For example, either number, or _name. Underscores come in handy when we want to create a compound word variable, such as: first_name, or you could write a compound variable name as lastName, this is called camel casing.
The standard Ruby convention is to use underscores to separate compound words. After the first letter or an underscore, a variable can contain either other letters or numbers, but no other special symbols. The special symbols on your keyboard usually have special meanings in Ruby, so it’s best to save them only for their specific use. For example, global variables are created by putting a dollar sign before the variable name, like $salary=10000.
Constants are variables that hold the same value throughout a program, although in Ruby you are able to reassign constants. You write a constant in all uppercase letters: PI=3.14159. They are written in all uppercase letters so that they are called out or are easily recognizable in a program so that when you’re scanning a program listing, you see a variable in all uppercase and you know right away that’s a constant. One of the differences with Ruby and constants and all other programming languages is that you can actually reassign a constant. Even though you can define constants in Ruby, you can also change their value. You should understand that they are used because you want that object to hold the same value throughout the program. By writing a constant in all uppercase you’re making it clear to anyone else reading the program that that variable is actually a constant and it’s value should not change.
To learn more and see these concepts demonstrated onscreen, here’s Mike’s lesson from chapter 3 of our Ruby Programming training course.