Ruby/Language Basics/Comparison Operators

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

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. 
c              Returns 0 if x and y are equal, 1 if x is higher, -1 if y is higher.
x != y         Not equal to.



Comparable module uses the <=> operator on the class that includes it.

<=> returns -1 if the supplied parameter is higher than the object"s value, 
            0 if they are equal, or 
            1 if the object"s value is higher than the parameter.
puts 1 <=> 2
puts 1 <=> 1
puts 2 <=> 1



Comparison Operators and Expressions

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



Equality, Less Than, or Greater Than

# Test two numbers for equality with ==, eql?, or <=>
puts 12 == 24/2
puts 24.eql?(12*2)
puts 12 == 14
puts 12 <=> 12
puts 12 <=> 10
puts 12 <=> 14



The == and eql? return true or false

# the <=> (spaceship operator) returns -1, 0, or 1, 
# depending on whether the first value is equal to the second (0), 
# less than the second (-1), or greater than the second (1).
# Test if two numbers are equal, less than, or greater than each other
puts 12 < 14 #less than
puts 12 < 12
puts 12 <= 12 # less than or equal to
puts 12.0 > 11.9
puts 12.0 >= 12 # greater than or equal to