O'Reilly logo

Ruby on Rails® for Microsoft Developers by Antonio Cangiano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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), ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required