Ruby - Comparison Operators and Expressions

Introduction

A Full List of Number Comparison Operators in Ruby

Comparison Meaning
x > y Greater than
x < y Less than
x == y Equal to
x >= y Greater than or equal to
x <= y Less than or equal to
x <=> y Comparison; returns 0 if x and y are equal, 1 if x is higher, and -1 if y is higher
x != y Not equal to

Consider the following code:

Demo

age = 10 
puts "You're too young to use this system" if age < 18 

age = 24 # from  ww w .ja va2s. co  m
puts "You're a teenager" if age > 12 && age < 20

Result

To get the opposite effect, you can use the word unless:

Demo

age = 24 
puts "You're NOT a teenager" unless age > 12 && age < 20

Result

You can also test for equality:

Demo

age = 24 
puts "You're 24!" if age == 24

Result

It's possible to group multiple expressions into a single expression, as with the following:

Demo

age = 24 
puts "You're a teenager" if age > 12 && age < 20

&& is used to enforce that both age > 12 and age < 20 are true.

You can check whether one or the other is true by using ||, as so:

Demo

age = 24 
puts "You're either very young or very old" if age > 80 || age < 10

Grouping together multiple comparisons is also possible with a clever use of parentheses:

Demo

age = 24 

gender = 'male'# from ww w .  jav  a  2  s. c  o m
puts "A very young or old man" if gender == "male" && (age < 18 || age > 85)

This example checks if gender is equal to "male" and if age is under 18 or over 85.