Variables often hold text or numeric data. In ruby there are several types of variables, including strings and numeric variables.

Variables can be reused in your code. Arithmetic operations can be used on numeric variables.

String variables can also be changed (sub-strings, concatenation).

Download Free Ruby Ebook

Variables in ruby

Numeric variables

Lets start with numeric variables. We create a program that calculates
the VAT for a given price.

Define a series of products, sum the price ex. VAT, then calculate the VAT and add it to the price.

Copy the code below and save the file as variables.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/ruby


pear = 3
coffee = 1
potato = 2

puts ""
total = pear + coffee + potato
puts "Price: #{total}"
vat = total * 0.15
puts "VAT: #{vat}"
price = total + vat
puts "Price (+VAT): #{price}"
puts ""

All arithmetic operations can be run on variables: division (/), substraction (-), addition (+) and multiplication (*)

Run with:

1
ruby variables.rb

Exercises

  1. Calculate the year given the date of birth and age
  2. Create a program that calculates the average weight of 5 people.