Project

General

Profile

Actions

Bug #22432

closed

Range#include? returns true for the end of an empty range of single-character Strings

Bug #22432: Range#include? returns true for the end of an empty range of single-character Strings

Added by sferik (Erik Berlin) about 1 month ago. Updated about 22 hours ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:127084]

Description

A Range whose ends are both single ASCII characters reports that it includes its end even when the range is empty.

r = "z".."a"
r.to_a          #=> []
r.include?("a") #=> true
r.member?("a")  #=> true
r.cover?("a")   #=> false
r === "a"       #=> false

I expect include? and member? to return false here, as cover? does and as iterating the range implies. The same happens with digits, for example ("1".."0").include?("0").

Only the end is affected. Other values are correctly reported as not included:

("z".."a").include?("z") #=> false
("z".."a").include?("m") #=> false

Range#include? has a shortcut for ranges of single-character Strings, which compares the characters instead of iterating. It is in rb_str_include_range_p in string.c:

if (ISASCII(b) && ISASCII(e) && ISASCII(v)) {
    if (b <= v && v < e) return Qtrue;
    return RBOOL(!RTEST(exclusive) && v == e);
}

The last line returns true whenever the value equals the end, without checking that the begin is not after the end.

Updated by sferik (Erik Berlin) about 1 month ago ยท Edited Actions #2 [ruby-core:127089]

@eightbitraptor (Matt V-H): Thanks. I previously submitted a nearly identical fix for this in https://github.com/ruby/ruby/pull/19313. CI is already green there.

Updated by nobu (Nobuyoshi Nakada) about 1 month ago Actions #3

  • Backport changed from 3.3: UNKNOWN, 3.4: UNKNOWN, 4.0: UNKNOWN to 3.3: REQUIRED, 3.4: REQUIRED, 4.0: REQUIRED

Updated by nagachika (Tomoyuki Chikanaga) about 1 month ago Actions #5 [ruby-core:127153]

  • Backport changed from 3.3: REQUIRED, 3.4: REQUIRED, 4.0: REQUIRED to 3.3: REQUIRED, 3.4: DONE, 4.0: REQUIRED

Thank you for creating PRs.
Merged into ruby_3_4at https://github.com/ruby/ruby/commit/26a4d835f7512f0615f6e0d7ed483c3438373b7e.

Updated by k0kubun (Takashi Kokubun) about 23 hours ago Actions #6 [ruby-core:127593]

  • Backport changed from 3.3: REQUIRED, 3.4: DONE, 4.0: REQUIRED to 3.3: REQUIRED, 3.4: DONE, 4.0: DONE

Updated by byroot (Jean Boussier) about 22 hours ago Actions #7

  • Status changed from Open to Closed
Actions

Also available in: PDF Atom