July 2007
Beginner to intermediate
176 pages
2h 30m
English
A conditional statement tests whether a statement is true or false and performs logic based on the answer. Both true and false are pseudovariables—you can’t assign values to them. The former is an object of TrueClass, and the latter is an object of FalseClass.
These statements begin with if and close with end:
ifx == ythenputs "x equals y"end ifx != y:puts "x is not equal to y"end ifx > y puts "x is greater than y"end
The separator then (or its synonym :) is optional unless the statement is on one line.
The negation operator ! reverses the true/false value of its expression:
if!x == y then puts "x does not equal y" end if!x > y puts "x is not greater than y" end
Combine multiple tests in an if statement using && and ||, or their synonyms and and or, which have lower precedence:
ruby = "nifty" programming = "fun" if ruby == "nifty" && programming == "fun" puts "Keep programming!" end if a == 10 && b == 27 && c == 43 && d == −14 print sum = a + b + c + d end if ruby=="nifty" and programming=="fun" and weather=="nice" puts "Stop programming and go outside for a break!" end if a == 10 || b == 27 || c = 43 || d = −14 print sum = a + b + c + d end if ruby == "nifty" or programming == "fun" puts "Keep programming!" end
You can also use if as a statement modifier by placing the if at the end of the statement:
puts "x is less than y" if x < yAdd an optional else to execute a statement ...
Read now
Unlock full access