Ruby Tutorial Ruby References

Ruby - comparison operators example



The example below illustrates the usage of Ruby comparison operators: ==, !=, >, <, >=, <=, <=> and .eql?.

puts "10 == 10: #{10 == 10}"
puts "10 != 10: #{10 != 10}"
puts "(1..20) === 10.0: #{(1..20) === 10.0}"
puts "10 < 20: #{10 < 20}"
puts "10 > 20: #{10 > 20}"
puts "10 <= 20: #{10 <= 20}"
puts "10 >= 20: #{10 >= 20}"

puts "\nCombined Comparison Operator\n"
puts "10 <=> 20: #{10 <=> 20}"
puts "20 <=> 20: #{20 <=> 20}"
puts "30 <=> 20: #{30 <=> 20}"

puts "\n.eql? Operator\n"
puts "10 == 10.0: #{10 == 10.0}"
puts "10 .eql? 10: #{10 .eql? 10.0}"

The output of the above code will be:

10 == 10: true
10 != 10: false
(1..20) === 10.0: true
10 < 20: true
10 > 20: false
10 <= 20: true
10 >= 20: false

Combined Comparison Operator
10 <=> 20: -1
20 <=> 20: 0
30 <=> 20: 1

.eql? Operator
10 == 10.0: true
10 .eql? 10: false

These comparison operators generally return boolean results, which is very useful and can be used to construct conditional statement as shown in the example below:

def range_func(x)
  #&& operator is used to combine conditions
  #returns true only when x >= 10 and x <= 25
  if x >= 10 && x <= 25 then
    puts "#{x} belongs to range [10, 25]."
  else
    puts "#{x} do not belongs to range [10, 25]."
  end
end

range_func(15)
range_func(25)
range_func(50)

The output of the above code will be:

15 belongs to range [10, 25].
25 belongs to range [10, 25].
50 do not belongs to range [10, 25].

❮ Ruby - Operators

5