Open Ranges Are Now Supported By The Object#in? Method In Rails

Object#in?(another_object) method is not part of the Ruby standard library. Thanks to Rails, it’s a convenience method added to the Object class to check if an object is included in another object.

This method returns true if the calling object is found within the argument provided. The argument must be any object that responds to the #include? method, which is a common method used to determine whether a collection or data structure contains a specific element.

fruits = ["Apple", "Mango", "Orange"]
"Apple".in?(fruits) # => true

Before

Verifying objects like strings, numbers, and hash works properly with Object#in? but if we use Object#in? to check if a date is present in an open date range, in Ruby 3.1, it never provides a result owing to the infinite loop, on the other hand, in Ruby 3.2, it raises a TypeError.

irb(main):001:0> Date.today.in?(Date.tomorrow..) 
=> .rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activesupport-7.0.4.3/lib/active_support/core_ext/range/compare_range.rb:51:in 

`include?': cannot determine inclusion in beginless/endless ranges (TypeError)
irb(main):002:0> 

To check if a date is present in an open date range, we should use the cover? method instead. The cover? method will return true if the date is within the range, and false otherwise.

((Date.today + 1)..).cover?(Date.today) #=> false, immediately

After

In the upcoming version of Rails, it is possible to check if a date is present in an open date range with Object#in?

This Pull Request changes Object#in? behavior to properly handle open date ranges i.e. beginless and endless ranges.

Under the hood Object#in? leverages Range#cover? instead of Range#include to properly handle beginless and endless date range inclusion checks.

Date.today.in?(Date.tomorrow..) => false
((Date.today + 1)..).in?(Date.today..) => true

Need help on your Ruby on Rails or React project?

Join Our Newsletter