iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💎

Ruby 3.2 - String / Encoding / Unicode

に公開

This is the article for day 11 of the Ruby 3.2 Advent Calendar.

https://qiita.com/advent-calendar/2022/ruby32


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

Feature #18949: Deprecate and remove replicate and dummy encodings - Ruby master - Ruby Issue Tracking System

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

Feature #18639: Update Unicode data to Unicode Version 15.0.0 - Ruby master - Ruby Issue Tracking System

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