Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Range#cover?

rng.cover?(obj) → true or false
rng.cover?(range) → true or false

Returns true if obj is between the begin and end of the range.

This tests begin <= obj <= end when exclude_end? is false and begin <= obj < end when exclude_end? is true.

If called with a Range argument, returns true when the given range is covered by the receiver, by comparing the begin and end values. If the argument can be treated as a sequence, this method treats it that way. In the specific case of (a..b).cover?(c...d) with a <= c && b < d, the end of the sequence must be calculated, which may exhibit poor performance if c is non-numeric. Returns false if the begin value of the range is larger than the end value. Also returns false if one of the internal calls to <=> returns nil (indicating the objects are not comparable).

Example
("a".."z").cover?("c")  #=> true
("a".."z").cover?("5")  #=> false
("a".."z").cover?("cc") #=> true
("a".."z").cover?(1)    #=> false
(1..5).cover?(2..3)     #=> true
(1..5).cover?(0..6)     #=> false
(1..5).cover?(1...6)    #=> true
See also #count #each #bsearch #end also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1