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"

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"

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!"

if a == 10 && b == 27 && c == 43 && d == −14
  print sum = a + b + c + d

if ruby=="nifty" and programming=="fun" and
  puts "Stop programming and go outside for a break!"

if a == 10 || b == 27 || c = 43 || d = −14
  print sum = a + b + c + d

if ruby == "nifty" or programming == "fun"
  puts "Keep programming!"

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 live online training, plus books, videos, and digital content from nearly 200 publishers.