4.2. Conditionals

Ruby offers several conditional statements and control structures for managing the flow of your applications. In the previous chapter you had a sneak peak at the if and for statements; here they are introduced more formally, among others useful statements.

4.2.1. if / elsif / else / unless

The following illustrates the usage of the if conditional statement in Ruby:

if temperature < 0
  puts "Freezing!"
end

Visual Basic programmers will find this syntax quite natural, and it shouldn't be too foreign to C# programmers either.

Any code between the if and the end line is executed unless the tested expression evaluates to false or nil. The if statement also accepts the then token separator (as opposed to the newline alone), so you could have written the same code as follows:

if (temperature < 0) then
  puts "Freezing!"
end

Parenthesis around expressions within conditional statements are optional in Ruby, but it may not be a bad idea to include them when they're helpful in clarifying the meaning of the code. Or even as a single line:

if temperature < 0 then puts "Freezing!" end

Ruby 1.8 allows semicolons as token separators as well, but Ruby 1.9 doesn't.

Listing 4-1 shows a recursive version of the factorial in Ruby.

Example 4.1. Naïve Factorial in Ruby
# Naive, recursive implementation of the factorial in Ruby

def fact(n)
  if n <= 1
    1
  else
    n * fact(n-1)
  end
end

n = (ARGV[0] || 10).to_i
puts fact(n)

Copy the code into a fact.rb file (or whatever you wish to call it), ...

Get Ruby on Rails® for Microsoft Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.