A variable in Ruby is like a labeled container - It's given a name, and then you use it in your programs to temporarily store and manipulate data. The variable naming scheme is simple. You may use any combination of lowercase letters, numbers or underscores to name your variables (label the container). It is generally a good idea to name your variables in such a way that you can easily identify what they're for, or at least in what context they're being used. The following examples are all valid Ruby variable names, and easily read:
More Perl Quick Tips
total_costYou can assign a value to any variable using the = method:
average_weight
the_answer
total_cost = '25 cents'Technically speaking, everything in Ruby is an object, and you interact with an object by calling it's methods. The above example is using the = method shorthand to assign a value to (in this case) a string object. The example could also be written like this:
average_weight = '40 lbs'
the_answer = 42
total_cost.=('25 cents')Among many other things, a Ruby variable could also contain an array or a hash:
average_weight.=('40 lbs')
the_answer.=(42)
several_names = ['Larry', 'Curly', 'Moe']
bobs_contact_information = { 'name' => 'Bob', 'phone' => '111-111-1111' }
- A variable in Ruby is just a label for a container.
- A variable could contain almost anything - a string, an array, a hash.
- A variable name may only contain lowercase letters, numbers, and underscores.
- A variable name should ideally make sense in the context of your program.
