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.
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.
# Naive, recursive implementation of the factorial in Ruby def fact(n) if n <= 1 1 else n * fact(n-1) end end n = (ARGV || 10).to_i puts fact(n)
Copy the code into a fact.rb file (or whatever you wish to call it), ...