dreamsys software

Ruby Scripting Tutorial


TOC | Introduction | Variables | If/Else | OptionParser | Looping | Functions | Classes | Strings | Lists & Maps | Shell

Variables


Variables are an important part of any program or script. A variable is a simple way to refer to a chunk of data in memory that can be modified. A variable in a ruby script can be assigned any type of value, such as a text string or a number. In ruby to create a variable, we simply put in our script:

$variableName = value

The text "$variableName" can be anything you want, as long as it only contains numbers, letters and/or an underscore "_". A variable name also cannot start with a number. After the equal sign you put the value. Let's revise our original script to use a couple of variables as such:

#!/usr/bin/ruby
# This is my second script.

$hello = 'Hello'
$ruby = 'Ruby!'

puts "#$hello #$ruby"

This will give the output "Hello Ruby!". Notice that we created two variables in this script. One variable "hello" which holds the text "Hello" and a second variable named "ruby" which holds the text "Ruby!".

Notice that here we use the hash (#) before the variable name. If we didn't use this, it would print the text "$hello $ruby". The hash is required inside a string to inform it to use a variable.

This is not a very exciting use of variable I will admit, let's try something more interesting. Let's create a ruby script that will take a name and age as parameters. Then it will tell you how long it will be until you are 100 years old. The arguments can then be accessed by the ARGV variable, which is an array containing the command line arguments.

To access the values in an array, you use the [] operator. For instance, to access the first item in the command line, you would access ARGV[0]. Let's make our script take the 2 arguments name and age which will be indexes 0 and 1 respectively. We can assign these values to a named variable and then print them. We will create a 3rd variable called "diff", which will hold the number of years until you will be 100 years old.

Note that before using the ARGV[1] as an integer, you must first call .to_i, this will convert the string to an integer.

#!/usr/bin/ruby
# Years till 100

$name = ARGV[0]
$age = ARGV[1].to_i
$diff = 100 - $age

puts "Hello #$name, you will be 100 in #$diff years!"

Give this program a name of years.rb, be sure to give it execute permission and then run it with the following command:

./years.rb Joe 25

This will print the text "Hello Joe, you will be 100 in 75 years!"

This script works well, but it does have some problems. For instance, what if you are 102 years old? What if you don't enter a name or an age on the command line? The script will either crash or print nonsense data. In order to fix this script, we will need to make use of the if and else keywords, which are covered in the next section.

Prev (Introduction) | Next (If/Else)