Our Daily Method #1: Range#coerce

Geplaatst door Michiel de Mare di, 05 feb 2008 08:00:00 GMT

We’d like to introduce a new blog category: Our Daily Method. We’ll demonstrate short, general purpose methods, which might be suitable for the standard library. We’re accepting requests!

We’ll kick off with Range#coerce. The problem is: you’ve got a value and you wish to ensure that it’s within a certain interval. Sounds ideal for a Range, but it’s missing from Ruby’s Range, although there’s include? (and in Ruby 1.9 cover?) to test whether the value is in the range.

Hence the following:

class Range
  def coerce(x)
    x < first ? first : x > last ? last : x
  end
end

(1..12).coerce(999)   # => 12

Recommend Michiel de Mare

Geplaatst in , ,  | geen reacties

Reacties

(Laat url/e-mail achter »)

   Voorvertoning