Read more

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

Henning Koch
March 09, 2011Software engineer at makandra GmbH

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.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Henning Koch to makandra dev (2011-03-09 18:22)