Snippet: Range#compare

Here’s a little idea that popped into my head for enhancing the Range class in Ruby:

1
2
3
4
5
6
7
8
9
10
11
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:

1
2
3
4
5
6
7
8
9
10
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:

1
2
3
4
5
6
>> 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.