Introduction To Ruby
Returning A Value From If

A nice feature of Ruby is the elegant way that you can refactor your code. The following exploits the fact that if statements are, in themselves, expressions in Ruby. That allows you to do neat things like the following,

# If returning a value

print "Enter the number of the month: "
monthnum = gets.chomp.to_i # get month number and convert to integer

monthname = if monthnum==1 then "January"
  elsif monthnum==2 then "February"
  elsif monthnum==3 then "March"
  else "Didn't fancy writing them all out"

puts monthname


Obviously, you could finish this program if you wanted.


Rewrite the following programs using the technique described on this page.

  1. Write a program that accepts two numbers as input from the user. Allow the user to specify whether to add or multiply the two numbers.
  2. Adapt your first program to include all four basic arithmetic operations. Use elsif statements to make it happen.
  3. Write a program that allows the user to input 2 numbers, A and B. Output one of the following statements.
    • A is greater than B
    • A is less than B
    • A and B are equal