Perl

  1. Home
  2. Computing & Technology
  3. Perl

A short introduction to variables in Ruby - Beginning Ruby Tutorial

Ruby Variables

From About.com

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:
total_cost
average_weight
the_answer
You can assign a value to any variable using the = method:
total_cost = '25 cents'
average_weight = '40 lbs'
the_answer = 42
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:
total_cost.=('25 cents')
average_weight.=('40 lbs')
the_answer.=(42)
Among many other things, a Ruby variable could also contain an array or a hash:
several_names = ['Larry', 'Curly', 'Moe']
bobs_contact_information = { 'name' => 'Bob', 'phone' => '111-111-1111' }
  1. A variable in Ruby is just a label for a container.
  2. A variable could contain almost anything - a string, an array, a hash.
  3. A variable name may only contain lowercase letters, numbers, and underscores.
  4. A variable name should ideally make sense in the context of your program.
More Perl Quick Tips

Explore Perl

More from About.com

Perl

  1. Home
  2. Computing & Technology
  3. Perl
  4. Similar Languages
  5. A short introduction to variables in Ruby, and how they are assigned

©2009 About.com, a part of The New York Times Company.

All rights reserved.