Project

General

Profile

Actions

Bug #18580

open

Range#include? inconsistency for beginless String ranges

Added by zverok (Victor Shepelev) 3 months ago. Updated 3 months ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:107547]

Description

The follow-up of #18577.

Range#include? is specialized for strings. For all I can tell, this behavior is relatively new: it emerged when switching #=== to use #cover? instead of #include?:

  • in 2.6, it was decided that String Ranges should continue to use #include? (#14575)
  • ...but in 2.7, it was decided that they should use #cover? as all others (#15449)

The "despecialization" in 2.7 was actually done by adding more specialization in range_include_internal.

This leads to the following:

# default Range behavior:
(..Date.today).include? Date.today
# (irb):10:in `each': can't iterate from NilClass (TypeError)

# String Range behavior:
(..'z').include?('w')
# => true 

Why I think it is bad:

  1. This is a leftover of the relatively recent change; why it is 3 versions old, I doubt there is a lot of code relying on this quirk (only beginless ranges are affected)
  2. The more "invisible specialization", the more possibility of bugs (as #18577 shows)
  3. It is easy to stumble upon while learning Ruby/experimenting (strings and ranges are the most basic objects to be seen in many examples and courses), and to become confused, because there is no reasonable explanation for the semantics other than "well... for String, it is so"
  4. It can be said that the String ranges behavior have the same specialization as Numeric ones, but it is not so; while Numeric Ranges specialization is long-living legacy, it is at least consistent (#include? just behaves like #cover? for them, always):

Numerics:

(1...3).include? 1.5
# => true, like #cover?

(...3).include? 1.5
# => true, same, the explanation is "just like #cover?"

Strings:

('a'..'z').include?('ww')
# => false, like #include? for any other type

(..'z').include?('ww')
# => true, this is deeply confusing
Actions #1

Updated by zverok (Victor Shepelev) 3 months ago

  • Subject changed from Range#include? inconsistency for String ranges to Range#include? inconsistency for beginless String ranges

Updated by jeremyevans0 (Jeremy Evans) 3 months ago

This was discussed during the February 2022 developer meeting, and @matz (Yukihiro Matsumoto) said he needs more time to consider it.

Actions

Also available in: Atom PDF