# Comparison operations in case statements

**URL:** <https://www.ruby-forum.com/t/comparison-operations-in-case-statements/52475>\
**Category:** Ruby\
**Created:** [January 14, 2006, 9:01pm UTC](https://www.ruby-forum.com/t/comparison-operations-in-case-statements/52475 "2006-01-14T21:01:21Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Joel\_VanderWerf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e19b73/32.png) [@Joel\_VanderWerf](https://www.ruby-forum.com/u/Joel_VanderWerf)\
**Post date:** [January 14, 2006, 9:01pm UTC](https://www.ruby-forum.com/t/comparison-operations-in-case-statements/52475/1 "2006-01-14T21:01:21Z")

</div>

This looks kind of cute, as a way to mix class-matching tests with  
comparison operator tests in case statements. Too bad it’s not really  
practical (the commented out caching may help a bit, but may also use  
too much memory):

class Comparator \< Proc  
def ===(val)  
call val  
end

def &(other)  
compare do |val|  
self[val] and other[val]  
end  
end  
end

def compare  
Comparator.new  
end

class Numeric  
#@comparator\_lt = {}  
def self.\<(x)  
#@comparator\_lt[x] ||=  
compare do |val|  
self === val and val \< x  
end  
end

#@comparator\_gt = {}  
def self.\>(x)  
#@comparator\_gt[x] ||=  
compare do |val|  
self === val and val \> x  
end  
end  
end

raise unless (Numeric \< 6) === 3  
raise if (Integer \< 6) === 2.3  
raise if (Integer \< 6) === “foo”

case 3  
when (Numeric \< 6) & (Numeric \> 5); raise  
when (Numeric \< 0) & (Numeric \> -10); raise  
when (Numeric \< 6) & (Numeric \> 2)  
else raise  
end

---

<div class="post-metadata">

**Author:** ![Joel\_VanderWerf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e19b73/32.png) [@Joel\_VanderWerf](https://www.ruby-forum.com/u/Joel_VanderWerf)\
**Post date:** [January 14, 2006, 10:34pm UTC](https://www.ruby-forum.com/t/comparison-operations-in-case-statements/52475/2 "2006-01-14T22:34:41Z")

</div>

On Jan 14, 2006, at 3:00 PM, Joel VanderWerf wrote:

> def self.\>(x)  
> raise if (Integer \< 6) === “foo”

Neat. Seems a little redundant though

raise unless Numeric === 3  
case  
when 3 \< 6 and 3 \> 5; raise  
when 3 \< 0 and 3 \> -10; raise  
when 3 \< 6 and 3 \> 2  
else raise  
end

I’m presuming nine times out of ten the variable you’ll run these  
tests on will have less characters than Numeric for instance.

eg:  
x = 3  
raise unless Numeric === x  
case  
when x \> 2; …  
end
