Home
Search
if Examples: elsif, else and unlessUse the if-statement, elsif and else. See the unless statement.
Ruby
This page was last reviewed on Nov 17, 2022.
If, else. In Ruby we use if-statements to test values. We can test multiple values at once, and use other logical operators like "or."
Statement notes. In a selection statement we direct the flow of control. In Ruby we use the "if" keyword. With elsif and else we handle alternative branches. An end is required.
case
If example. After the if-keyword we place an expression. Ruby then checks whether this statement evaluates to true or false. If it evaluates to true, the inner block is entered.
However If the expression evaluates to false, the inner block of an if-statement is not reached. The statements are not executed.
# Some integer variables. a = 1 b = 2 c = 3 # Test for inequality. if a != b puts "1 != 2" end # Add and then test for equality. if a + b == c puts "1 + 2 == 3" end
1 != 2 1 + 2 == 3
Elsif, else. An if-statement can have more parts. It can include an elsif-statement and an else-statement. They are reached only when the initial if-statement evaluates to false.
Here The statement within the else-block is reached. The if and elseif evaluate to false, so "Z" is printed.
Tip For performance, putting the condition that matches most often first is fastest. Fewer conditions must be evaluated in total.
# Two integers. a = 1 b = 2 # Use if, elsif, else on the integers. if a > b # Not reached. print "X" elsif a == b # Not reached. print "Y" else # This is printed. print "Z" end
Z
One-line. Ruby supports one-line if-statements. The "if" is used to modify the preceding statement. These statements are only run if the if-expression evaluates to true.
Here The first statement has no effect because the variable is not greater than 5. But the second statement takes effect.
# Variable equals 5. i = 5 # Use one-line if-statements. puts "Greater than 5" if i > 5 puts "Not greater than 5" if i <= 5
Not greater than 5
Unless. This is a negated if-statement. It has the same functionality as an if-statement that tests for false, not true. But this syntactic sugar is sometimes useful.
Also There is an else-statement that can follow the unless statement. The syntax is just like an if-block.
i = 4 # Use an unless-else construct. unless i == 3 puts "UNLESS" else puts "ELSE" end
UNLESS
Unless, one line. An unless modifier can also be used on one line. This syntax makes programs readable, almost like English: you take a certain action unless a condition is true.
Here We display the value of the string with puts, unless the value equals Cat. So the value Dog is displayed.
animal = "Dog" # Display the animal string unless it equals Cat. puts animal unless animal == "Cat"
Dog
And, or. Sometimes we need to chain together expressions in an if-statement. We can use the "and" or "&&" operators. Two syntax forms for "or" are also supported.
Short-circuit These operators short-circuit. And will stop checking after its first false result, "or" after its first true.
Note The English operators (and, or) are easier to read. But the symbolic ones are more familiar to developers of C-like languages.
Note 2 The English operators have a lower precedence. For consistency the C-like operators may be a better choice.
animal1 = "cat" animal2 = "dog" # And operators. if animal1 == "cat" and animal2 == "dog" puts 1 end if animal1 == "cat" && animal2 == "dog" puts 2 end # Or operators. if animal1 == "whale" or animal2 == "dog" puts 3 end if animal1 == "whale" || animal2 == "dog" puts 4 end
1 2 3 4
And, or precedence. In the Ruby grammar there is an important difference between "and" and "&&" and the "or" versions. The English words have lower operator precedence.
Note In my testing, this does not affect many simple expressions. But the change in precedence could affect more complex things.
Program Consider the 2 if-expressions. The first has "and" which means the part after the "||" is evaluated together.
And The second if-statement has "&&" which means "top" is evaluated all by itself.
left = 0 top = 2 # Not true because "and" has lower precedence. if top == 2 || left == 0 and top == 3 puts "1" end # True because && has higher precedence. if top == 2 || left == 0 && top == 3 puts "2" end
2
If 1: (top == 2) (left == 0, top == 3) If 2: (top == 2, left == 0) (top == 3)
Ternary. This statement uses a question mark and a ":" after an expression. If the expression evaluates to true, the first result is chosen.
Otherwise The second value is used as the result. Here, the value equals 10, so the result is 20. The 0 is returned in all other cases.
value = 10 # Ternary statement. result = value == 10 ? 20 : 0 puts result
20
Equals. In an if-conditional, two equals signs check for equality. Ruby will report a warning if you use just one equals sign. An assignment uses one equals. A conditional, two.
But The program still compiles. In some languages, this syntax results in a fatal, compile-time error.
value = 10 # We should use two = in a conditional. if value = 20 puts true end
C:/programs/file.rb:6: warning: found = in conditional, should be ==
true
Assign. Like a method, an if-statement returns a value. This comes from the last statement evaluated. We can assign a variable to the result of an if-statement.
Result In this program, the variable cat_sound is assigned to "meow" because the size variable is equal to 0.
# Set size to zero. size = 0 # Assign cat_sound to result of if-statement. cat_sound = if size == 0 "meow" else "roar" end puts(cat_sound)
meow
Then. This keyword can be part of an if-statement. But usually in Ruby programs do not use the "then." This keyword may be preferred if makes the code clearer to read.
Note In programming, clarity is key. But standard forms—using Ruby that other developers also use—is also important.
value = 10 size = 10 # The "then" keyword is optional. if value == size then puts true end # Omit the then. if value == 10 puts 10 end
true 10
True, false. In an if-statement all values can be evaluated for truth. In this program, we test for truth. We test numbers, empty collections like arrays, and nil.
Numbers All numbers (including 0) evaluate to true. Other programming languages sometimes treat 0 as false, but not Ruby.
Empty array An empty Array evaluates also to true. Empty collections are treated the same as ones with elements.
Nil False and nil evaluate to false—these were the only false values found in this test.
values = [0, 1, -1, true, false, nil, Array.new()] # Test all the values for truth. values.each do |v| if v puts String(v) + " = true" else puts String(v) + " = false" end end
0 = true 1 = true -1 = true true = true false = false = false [] = true
A summary. The if-statement is an imperative branching statement. This means it affects what statements are next executed. Its effect is directly specified by the programmer.
Some concepts. With an if-statement, we create conditional blocks. The data in our programs influences what operations are taken. An elseif and else provide alternative paths.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 17, 2022 (simplify).
Home
© 2007-2022 sam allen.
see site info on the changelog.