In the first part of the series, Ruby Basics – Data Types, I introduced the more commonly used data types in the Ruby language. In this part, I am going to introduce variables, how they are used, and conventions in naming.
Variables are a part of almost all modern programming languages. They are used to store, hold, and return data. I like to think of a variable as an envelope; just like an envelope holds its contents, a variable holds it data. Envelopes come in various shapes, sizes, and colors, each catering to a particular use. While a regular letter envelope might hold a bill or letter from a friend, a catalog envelope might contain the latest issue of your favorite magazine or a new hire package from a new job.
Programming languages handle variable types in one of two ways, strongly or dynamically typed. Languages such as C++, C#, VB.Net, and Java are strongly typed languages. This means the data type for each variable must be declared, or specified, first and is not allowed to change. Only the type of data that matches the variable’s type can be stored in the variable. Just like different size envelopes for different contents, each variable is created and defined for a specific type of data.
Ruby is a dynamically typed language. This means variable types are not declared and that the interpreter resolves the data type based on the contents of the variable. All variables are objects. This would be like using an overnight envelope to hold any type of content and letting the post office figure out which type of envelope is needed when shipping, based on the contents of the envelope.
Imagine it is October and you are sitting down to get a start on your Christmas cards. You have your list of people to send cards to, a handful of cards, and two stacks of envelopes, one for standard mailing and the other larger envelope for international mailing. As you fill out each card, you put it into an envelope and label the envelope with something meaningful that will allow you to identify its contents at a glance. You label variables in the same way, with something meaningful that will allow you to identify its contents at a glance. Imagine labeling each envelope with a letter and number. Sure, you might remember its contents for that period of time you are filling out the cards, but will you remember the contents two months later when it is time to mail the cards or will you have to open the envelopes to remember the contents?
For additional information on variables, including samples, click here.