Conditional Statements

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.

The if Statement

These statements begin with if and close with end:

if x == y then puts "x equals y" end

if x != y: puts "x is not equal to y" end

if x > y
  puts "x is greater than y"
end

The separator then (or its synonym :) is optional unless the statement is on one line.

Negation

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

Multiple tests

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

Statement modifier for if

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 < y

The else statement

Add an optional else to execute a statement ...

Get Ruby Pocket Reference 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.