How to Use Comparison Operators in Ruby: Syntax and Examples
In Ruby, you use
==, !=, <, >, <=, and >= to compare values. These operators return true or false depending on the comparison result.Syntax
Ruby provides several comparison operators to compare values:
==: Checks if two values are equal.!=: Checks if two values are not equal.<: Checks if the left value is less than the right value.>: Checks if the left value is greater than the right value.<=: Checks if the left value is less than or equal to the right value.>=: Checks if the left value is greater than or equal to the right value.
ruby
a == b # equal to a != b # not equal to a < b # less than a > b # greater than a <= b # less than or equal to a >= b # greater than or equal to
Example
This example shows how to use comparison operators to compare numbers and strings. It prints the result of each comparison.
ruby
a = 5 b = 10 c = 5 puts a == b # false puts a == c # true puts a != b # true puts a < b # true puts b > c # true puts a <= c # true puts b >= a # true puts "apple" == "apple" # true puts "apple" != "orange" # true
Output
false
true
true
true
true
true
true
true
true
Common Pitfalls
One common mistake is using = (assignment) instead of == (comparison). Another is comparing different types without converting them, which can lead to unexpected results.
Always use == to check equality, not =.
ruby
x = 5 # Wrong: assignment instead of comparison if x = 10 puts "x is 10" else puts "x is not 10" end # Right: use == for comparison if x == 10 puts "x is 10" else puts "x is not 10" end
Output
x is 10
x is not 10
Quick Reference
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Equal to | 5 == 5 | true |
| != | Not equal to | 5 != 3 | true |
| < | Less than | 3 < 5 | true |
| > | Greater than | 5 > 3 | true |
| <= | Less than or equal to | 5 <= 5 | true |
| >= | Greater than or equal to | 5 >= 3 | true |
Key Takeaways
Use == to check if two values are equal and != to check if they are not equal.
Comparison operators return true or false based on the values compared.
Avoid using = when you mean to compare; = is for assignment.
Make sure to compare compatible types to avoid unexpected results.
Ruby supports <, >, <=, and >= for numeric and string comparisons.