4.4 If-Then-Else Statements

Ruby uses an if statement for basic conditional control flow.

Gem of Wisdom

An If-Then-Else statement or its equivalent is found in every programming language.

The basic form of an if statement is shown in Example 4-3.

Example 4-3. If statement
    1 if (condition)
    2 	# section 1
    3 end

The condition is a logical expression, as described previously; in Example 4-3, section 1 is executed when the condition evaluates to true, and it is skipped when the condition evaluates to false. An example of using the if statement is shown in Example 4-4. Given a number from the user, the program determines if the value is even. If it is, the program will print “Even” to the screen.

Example 4-4. Determine if the number is even
    1 # if a number is even, print out "Even"
    2 puts "Enter a number"	# print message
    3 number = gets.to_i	# get number as an integer
    4 if (number % 2 == 0)	# check if even
    5 	puts "Even"
    6 end

Assume the user inputs a value of 11. In this case, number will be equal to 11 when we try to evaluate the expression number % 2 == 0. This means that the flow option, shown on line 5, will not execute because the expression 11 % 2 == 0 will evaluate to false since 11 % 2 is equal to 1, not 0. Thus, nothing will be printed to the screen. If the user enters 10, then 10 % 2 == 0 will evaluate to true, meaning puts ''Even'' will be executed; the screen will display “Even.”

The if statement can be extended with the use of the else. The general form for the ...

Get Computer Science Programming Basics in Ruby 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.