Comparison
We've learned how to evaluate the truthiness of a statement and how to branch code based on that truthiness. The last foundational concept in conditional program flow is how to compare two variables. We need to be able to determine whether two variables are the same, are not the same, or are less than or greater than each other.
Let's look at the operators used for comparison in Ruby.
Comparison Operators
The following are the operators most commonly used for comparison in Ruby:
Let's now write a method that combines all of the concepts in this chapter. We will be comparing two variables, x
and y
, and putting them through different comparison conditions:
def compare(x, y) if x < y puts "#{x} < #{y}" elsif x <= y puts "#{x} <= #{y}" elsif x == y puts...