iTranslated by AI
Ruby 3.2 - String / Encoding / Unicode
This is the article for day 11 of the Ruby 3.2 Advent Calendar.
String
String#byteindex / String#byterindex
Feature #13110: Byte-based operations for String - Ruby master - Ruby Issue Tracking System
String#byteindex and String#byterindex have been added.
While #index and #rindex are character-based, #byteindex and #byterindex return indices in bytes.
'じゅげむじゅげむ'.index('げ') #=> 2
'じゅげむじゅげむ'.rindex('げ') #=> 6
'じゅげむじゅげむ'.byteindex('げ') #=> 6
'じゅげむじゅげむ'.byterindex('げ') #=> 18
String#bytesplice
Feature #18598: Add String#bytesplice - Ruby master - Ruby Issue Tracking System
String#bytesplice has been added.
It replaces characters at a specific byte position in a string.
s = 'abcdefg'
s.bytesplice(3, 3, '12345') #=> "12345"
# 'def' is replaced with '12345'
s #=> "abc12345g"
s = 'あいうえお'
s.bytesplice(3, 3, '12345') #=> "12345"
# 'い' is replaced with '12345'
s #=> "あ12345うえお"
For multi-byte characters, it results in an error if the position does not land on a character boundary.
s = 'あいうえお'
s.bytesplice(4, 1, 'x')
#=> offset 4 does not land on character boundary (IndexError)
Encoding
Encoding#replicate has been deprecated and is scheduled for removal in Ruby 3.3.
A warning is issued when running with the -w flag.
% ruby -w -e 'Encoding::UTF_8.replicate("hoge")'
-e:1: warning: Encoding#replicate is deprecated and will be removed in Ruby 3.3; use the original encoding instead
I have never used Encoding#replicate, so I am not sure what it was intended for.
Unicode 15.0.0 / Emoji 15.0
Unicode 15.0.0 and Emoji 15.0 are now supported. Ruby 3.1 supported Unicode 13.0.0 and Emoji 13.0.
Ruby 3.1
'😀🫠😇🫨'.inspect #=> "😀\u{1FAE0}😇\u{1FAE8}"
Ruby 3.2
'😀🫠😇🫨'.inspect #=> "😀🫠😇🫨"
Discussion