A conditional statement tests whether a statement is
false and performs logic based on the answer. Both
false are pseudovariables—you can’t assign values to them. The former is an object of
TrueClass, and the latter is an object of
These statements begin with
if and close with
ifx == y
thenputs "x equals y"
end ifx != y
:puts "x is not equal to y"
end ifx > y puts "x is greater than y"
then (or its synonym :) is optional unless the statement is on one line.
The negation operator
! reverses the
false value of its expression:
!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
||, or their synonyms
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"
ifx < y
Add an optional
else to execute a statement ...