Skip to content

Commit

Permalink
Implement Comparable.
Browse files Browse the repository at this point in the history
[git-p4: depot-paths = "//src/metaruby/dev/": change = 2192]
  • Loading branch information
drbrain committed Oct 15, 2005
1 parent 2c40a32 commit c239808
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
78 changes: 78 additions & 0 deletions Comparable.rb
@@ -0,0 +1,78 @@
module Comparable

##
# call-seq:
# obj < other => true or false
#
# Compares two objects based on the receiver's <tt><=></tt> method,
# returning true if it returns -1.

def <(other)
return (self <=> other) == -1
end

##
# call-seq:
# obj <= other => true or false
#
# Compares two objects based on the receiver's <tt><=></tt> method,
# returning true if it returns -1 or 0.

def <=(other)
return ((self <=> other) == -1 or (self <=> other) == 0)
end

##
# call-seq:
# obj == other => true or false
#
# Compares two objects based on the receiver's <tt><=></tt> method,
# returning true if it returns 0. Also returns true if <em>obj</em> and
# <em>other</em> are the same object.

def ==(other)
return (self <=> other) == 0
end

##
# call-seq:
# obj > other => true or false
#
# Compares two objects based on the receiver's <tt><=></tt> method,
# returning true if it returns 1.

def >(other)
return (self <=> other) == 1
end

##
# call-seq:
# obj >= other => true or false
#
# Compares two objects based on the receiver's <tt><=></tt> method,
# returning true if it returns 0 or 1.

def >=(other)
return ((self <=> other) == 1 or (self <=> other) == 0)
end

##
# call-seq:
# obj.between?(min, max) => true or false
#
# Returns <tt>false</tt> if <em>obj</em> <tt><=></tt> <em>min</em> is less
# than zero or if <em>anObject</em> <tt><=></tt> <em>max</em> is greater
# than zero, <tt>true</tt> otherwise.
#
# 3.between?(1, 5) #=> true
# 6.between?(1, 5) #=> false
# 'cat'.between?('ant', 'dog') #=> true
# 'gnu'.between?('ant', 'dog') #=> false

def between?(min, max)
return ((self <=> min) >= 0 and (self <=> max) <= 0)
raise NotImplementedError, 'between? is not implemented'
end

end

1 change: 1 addition & 0 deletions Makefile
Expand Up @@ -18,6 +18,7 @@ CLASSES = \
Range \
Hash \
String \
Comparable \
$(NULL)

TESTFILES = $(patsubst %,%.pass,$(CLASSES))
Expand Down

0 comments on commit c239808

Please sign in to comment.