← Blog

Ruby 2.6 Range#cover? accepts Range object as argument

This blog is part of our Ruby 2.6 series.

Range#cover? returns true if the object passed as argument is in the range.

(1..10).cover?(5)
=> true

Range#cover? returns false if the object passed as an argument is non-comparable or is not in the range.

Before Ruby 2.6, Range#cover? used to return false if a Range object is passed as an argument.

>> (1..10).cover?(2..5)
=> false

Ruby 2.6

In Ruby 2.6 Range#cover? can accept a Range object as an argument. It returns true if the argument Range is equal to or a subset of the Range.

(1..100).cover?(10..20)
=> true

(1..10).cover?(2..5)
=> true

(5..).cover?(4..)
=> false

("a".."d").cover?("x".."z")
=> false

Here is relevant commit and discussion for this change.

Abhay Nikam avatar
Written byAbhay Nikam
Newsletter

Stay up to date with our blogs.

Subscribe to receive an email notification for a new blog post.