Skip to content

String#[]: implicit conversions for index, length, and range args - #443

Merged
tannevaled merged 1 commit into
mainfrom
feat/cluster15
Aug 24, 2026
Merged

tannevaled merged 1 commit into
mainfrom
feat/cluster15

Conversation

@tannevaled

Copy link
Copy Markdown
Contributor

String#[] (and, by delegation, Symbol#[]) now applies MRI's argument
conversions that the raw slice logic skipped:

  • a Float or #to_int object index/length converts to an Integer,
    truncating toward zero — "hello"[1.5] → "e", "hello"[1.5, 2.9] → "el";
  • a Range argument is accepted when it is a Range subclass or carries
    Float/#to_int bounds — "hello"[1.0..3.0] → "ell", "hello"[R.new(1,3)];
  • the substring form and the Integer/Regexp forms are unchanged.

The coercion lives in the strIndexFn wrapper (which has the VM to dispatch
#to_int), leaving the pure stringIndexEnc slice helper untouched. A Range
argument is builtin-unwrapped here because dispatch only unwraps a receiver,
not an argument.

The 1..2 arity is now validated for every form (including Regexp), matching
MRI's ArgumentError for 0 or 3+ arguments.

Verified against ruby 4.0.6. Full package coverage stays at 100.0%.
Zero-regression rubyspec sweep; +6 on core/string/element_reference and
+5 on core/symbol/element_reference.

🤖 Generated with Claude Code

… args

String#[] (and, by delegation, Symbol#[]) now runs MRI's argument coercions
that the raw slice logic skipped:

  - a Float or #to_int object index/length converts to an Integer, truncating
    toward zero ("hello"[1.5] => "e", "hello"[1.5, 2.9] => "el");
  - a Range argument is accepted when it is a Range subclass or carries
    Float/#to_int bounds ("hello"[1.0..3.0] => "ell", "hello"[R.new(1,3)]);
  - a lone String argument (the substring form) and the Integer/Regexp forms
    are unchanged.

The coercion runs in the strIndexFn wrapper (which has the VM to dispatch
#to_int), leaving the pure stringIndexEnc slice helper untouched. Range
arguments are builtin-unwrapped here because dispatch only unwraps a receiver,
not an argument.

The 1..2 arity is now validated for every form, including the Regexp form,
matching MRI's ArgumentError for 0 or 3+ arguments.

Verified against ruby 4.0.6. Zero-regression rubyspec sweep; +6 on
core/string/element_reference and +5 on core/symbol/element_reference.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@tannevaled
tannevaled merged commit 175ae87 into main Aug 24, 2026
7 checks passed
@tannevaled
tannevaled deleted the feat/cluster15 branch August 24, 2026 17:48
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