Ruby Comparable Made Simple

# Comparable test
class Testing
  include Enumerable
  include Comparable
  attr_accessor :a, :b, :c

  def initialize(a, b, c)
    @a = a
    @b = b
    @c = c
  end

  def each
    yield @a
    yield @b
    yield @c
  end

  # This method is called by the inherited comparison methods (viz. ==, >  # , <, between, etc to compare this Testing Object
  def <=>(other)
    @a + @b + @c <=> other.a + other.b + other.c
  end
end

t1 = Testing.new(1, 2, 3)
t2 = Testing.new(2, 3, 4)

if (t1 > t2)
  puts "T1 is greater"
else
  puts "T2 is greater"
end

t3 = Testing.new(2, 2, 2)

t3.between(t1, t2)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s