Aside from the features noted above, there are still things that you can do that will not only help you with Ruby variables, but also make your program more comprehensible. I thought I would share some of the Do’s and Don’ts that have helped me over the last few months.
- Make your variable names meaningful. The names of your variables should be descriptive of the data assigned to it. Not only will it be easier for you to understand what that variable points to, but it will be easier for your co-workers to understand what that variable points to. This is considered a good practice and will probably earn you a lot more friends.
- Do use the #local_variables method. Variables are subject to scope, whether you like it or not. This is a great way to find out what variables are in the scope of the part of the program you are working in. Knowing is half the battle.
- Do not begin a variable with a number. Not only should you not do this, but you CAN’T do this. This is so the interpreter can distinguish between a variable and an integer. Don’t confuse the interpreter. The interpreter is your friend. Although, you can’t begin a variable with a number, Ruby does accept an underscore as the beginning of a variable.
- Do not begin a variable with an uppercase letter. Ruby is case-sensitive. Variables must begin with a lowercase letter. To do otherwise would be to create a Constant. Constants are just that, constant. They aren’t supposed to be changed throughout the duration of the program (although, they can be. We will get into this in a future post). Avoiding uppercase letters in your variables will help you avoid unwanted headaches.
- Do not use global variables. Ok, this is not a hard and fast rule. Global variables can be useful at times, but the majority of times they just make things more difficult. Global variables are named as such because they have a global scope. This means that you can access that variable anywhere in your program that your little heart desires. Try to limit the use of these in your programs.
- Don’t use single letter variables. I somewhat covered this already in #1 of the “Do’s”, but I think this is so important it should be said twice. Variable names should be meaningful. Assigning the letter “a” to a gets#chomp method on a string requesting user input is just mean. Don’t be mean.
If you follow this short list of Do’s and Don’ts, you will be rocking Ruby variables like a superstar. Stay strong. Stay focused….and don’t use single letter variables. Unless, of course, you don’t like having friends.