BigBinary Blog

We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.

Ruby 2.6 Range#cover? accepts Range object as argument

This blog is part of our Ruby 2.6 series.

Ruby 2.6.0 was released on Dec 25, 2018.

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.

Abhay Nikam in Ruby 2.6
October 24, 2018
Share

Subscribe to our newsletter