Commit df20643c

df20643c4ae5Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 8 months ago · 2 files · +1 added · ~1 modified

Description

Add sp_String methods: replace, clear, [], gsub, split, +, to_s

Extend the mutable string type with additional Ruby-compatible methods:

  • replace(str): in-place content replacement
  • clear: empties string (len=0)
  • [n]: character access via sp_String_char_at
  • gsub(from, to): delegates to sp_str_gsub on underlying cstr
  • split(delim): delegates to sp_str_split on underlying cstr
    • str: non-mutating concat returning new const char *
  • to_s: returns underlying cstr (already existed, now in infer_type)

Also widens STRING to SP_STRING when replace/clear are called, matching the existing << widening behavior.

Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]

Details

Commit
df20643c4ae5
Parent
108a3fc8dc97

examples/bm_mutable_str2.rbaddedView file

1+# Test sp_String additional methods
2+
3+# replace
4+s = "hello"
5+s.replace("world")
6+puts s # world
7+
8+# clear
9+s.clear
10+puts s.length # 0
11+
12+# [] on mutable string
13+s2 = "abcdef"
14+s2 << "ghi"
15+puts s2[0] # a
16+puts s2[-1] # i
17+puts s2.length # 9
18+
19+# gsub on mutable string
20+s3 = "hello"
21+s3 << " world"
22+puts s3.gsub("o", "0") # hell0 w0rld
23+
24+# split on mutable string
25+s4 = "a"
26+s4 << ",b,c"
27+parts = s4.split(",")
28+puts parts.length # 3
29+
30+# + on mutable (creates new string, does not mutate)
31+s5 = "foo"
32+s5 << "bar"
33+s6 = s5 + "baz"
34+puts s5 # foobar (unchanged)
35+puts s6 # foobarbaz
36+
37+# to_s
38+s7 = "test"
39+s7 << "ing"
40+puts s7.to_s # testing
41+
42+puts "done"