Skip to content

Fix Range#include? of an empty range of single characters - #9846

Open
sferik wants to merge 1 commit into
jruby:masterfrom
sferik:range-include-empty-single-char
Open

sferik wants to merge 1 commit into
jruby:masterfrom
sferik:range-include-empty-single-char

Conversation

@sferik

@sferik sferik commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

This ports ruby/ruby#19313 from CRuby, which fixes Bug #22432.

A range whose ends are both single ASCII characters says it includes its end even when the range is empty:

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

RubyString.includeRange has the same shortcut as CRuby's rb_str_include_range_p: for this kind of range, it compares the characters directly instead of iterating. Its last check returns true when the value equals the end, without checking that the begin is not after the end. This adds that check, so include? and member? agree with to_a, each and cover?. JRuby 9.4.15.0, 10.0.7.0 and 10.1.2.0 all have the bug.

The tests are the ones from the CRuby PR, added to test/mri/ruby/test_range.rb. The new assertions fail on 10.1.2.0, and with this change all of test_range.rb and the Range specs in ruby/spec pass.

The CRuby fix has already been backported to Ruby 3.4, is marked for backport to 4.0, and will be in Ruby 4.1, so it should be safe to port to JRuby now. It might be worth backporting to JRuby 10.0 and 9.4, too. Please let me know if you want me to open backport PRs for those older releases as well.

A range whose ends are both single ASCII characters said it included
its end even when the range was empty, so ("z".."a").include?("a")
returned true while to_a was empty and cover?("a") returned false.

RubyString.includeRange compares the characters directly for this kind
of range instead of iterating, and its last check returned true when
the value equaled the end without checking that the begin isn't after
the end. Add that check, so include? and member? agree with to_a, each
and cover?.

This ports ruby/ruby#19313 from CRuby, which
fixes https://bugs.ruby-lang.org/issues/22432, including its tests.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant