Ruby 2.6 Range#cover? accepts Range object as argument

Abhay Nikam

Abhay Nikam

October 24, 2018

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(1..10).cover?(5)
2=> 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>> (1..10).cover?(2..5)
2=> 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(1..100).cover?(10..20)
2=> true
3
4(1..10).cover?(2..5)
5=> true
6
7(5..).cover?(4..)
8=> false
9
10("a".."d").cover?("x".."z")
11=> false

Here is relevant commit and discussion for this change.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.