Check that a Range covers an element in both Ruby 1.9 and 1.8.7

Updated . Posted . Visible to the public.

In order to cover some edge cases you rarely care about, Range#include? will become very slow in Ruby 1.9 Show archive.org snapshot :

Range#include? behaviour has changed in ruby 1.9 for non-numeric ranges. Rather than a greater-than/less-than check against the min and max values, the range is iterated over from min until the test value is found (or max) [...] Ruby 1.9 introduces a new method Range#cover? that implements the old include? behaviour, however this method isn’t available in 1.8.7.

The attached code will add a Range#cover? method to your Ruby 1.8.7 and not do anything in Ruby 1.9+. This way you can always use cover? now and don't need to change your code when you switch to Ruby 1.9.

Henning Koch
Last edit
Attachments
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-03-09 17:22)