Introduction To Ruby
Unless Statements

The unless statement is the opposite of if. It executes code if the main condition evaluates to false or nil. It does not allow elsif clauses. There are times when the most likely outcome of a conditional statement is false. Code reads more easily in these cases when you use an unless statement.

Example 1

# Unless

print "Do you want me to say hello?: "
choice = gets.chomp
unless choice=="no" then
  puts "Hello"
end

gets

Example 2

The unless statement can be used with an else clause.

# Unless...else

print "Do you want me to say hello?: "
choice = gets.chomp
unless choice=="no" then
  puts "Hello"
else
  puts "Goodbye"
end

gets

Example 3

You can also use unless as a modifier.

# Unless as a modifier

print "Do you want me to say hello?: "
choice = gets.chomp
puts "Hello" unless choice=="no"

gets