Skip to Content
Ruby on Rails® for Microsoft Developers
book

Ruby on Rails® for Microsoft Developers

by Antonio Cangiano
April 2009
Intermediate to advanced content levelIntermediate to advanced
479 pages
12h 55m
English
Wrox
Content preview from Ruby on Rails® for Microsoft Developers

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Michael Hartl

Publisher Resources

ISBN: 9780470374955Purchase book