2.8. if-Condition

An abstract if-condition looks like this:
if expression
  program
end
The program between the expression and end is executed if the result of the expression is not false and not nil.

Note

You can also use a then after the expression:
if expression then
  program
end
The construct for a simple if-branch in a Ruby program looks like the following example program:
a = 10

if a == 10
  puts 'a is 10'
end

Note

The '==' is used to compare two values. Please don't mix it up with the single '='.
You can try an expression really well in irb:
$ irb --simple-prompt
>> a = 10
=> 10
>> a == 10
=> true
>> exit
$

Shorthand

A frequently used shorthand notation of an if-condition can be found in the following code:
a = 10

# long version
#
if a == 10 then
  puts 'a is 10'
end

# short version
#
puts 'a is 10' if a == 10

else

You can probably imagine how this works, but for the sake of completeness, here is a little example:
a = 10

if a == 10 then
  puts 'a is 10'
else
  puts 'a is not 10'
end

elsif

Again, most programmers will know what this is all about. Example:
a = 10

if a == 10 then
  puts 'a is 10'
elsif a == 20 then
  puts 'a is 20'
end

Updates about this book will be published on my Twitter feed.