Ruby - Using Comparable module

Introduction

You can use Comparable module to define your own comparison "operators" as in <, <=, ==, >=, and >.

This is done by mixing the module into your class and defining the <=> method.

Demo

class Employee
       include Comparable# from   w w  w.  ja  va  2  s.c  om

       Names = ['A','B','C','D','E','F','G']

       attr_accessor :name

       def <=> (anOtherName)
            Names.index(@name)<=>Names.index(anOtherName.name)
       end

       def initialize( aName )
               @name = aName
       end

end


elf =  Employee.new('A')
orc = Employee.new('C')
giant = Employee.new('F')

puts( elf < orc )     #=> true
puts( elf > giant )   #=> false

Result

Related Topic