Snippet: Range#compare
Here's a little idea that popped into my head for enhancing the Range class in Ruby:
class Range
def compare( value )
if member?( value )
0
elsif value <= self.begin
-1
elsif value >= self.end
1
end
end
end
Then you can perform broad comparisons, like so:
def try_compare( x, r=(1..10) )
case r.compare x
when -1
"#{x} is below the range #{r}"
when 1
"#{x} is above the range #{r}"
when 0
"#{x} is inside the range #{r}"
end
end
Example:
>> try_compare( 3 ) "3 is inside the range 1..10" >> try_compare( -1 ) "-1 is below the range 1..10" >> try_compare( 11 ) "11 is above the range 1..10"
I haven't decided whether this is useful, or just daft.