Ruby 3.2 - String / Encoding / ユニコード

Ruby 3.2 アドベントカレンダーの11日目の記事です。

qiita.com


String

String#byteindex / String#byterindex

Feature #13110: Byte-based operations for String - Ruby master - Ruby Issue Tracking System

String#byteindex, String#byterindex が追加された。

#index, #rindex は文字単位だけど、#byteindex, #byterindex はバイト単位のインデックスを返す。

'じゅげむじゅげむ'.index('')      #=> 2
'じゅげむじゅげむ'.rindex('')     #=> 6
'じゅげむじゅげむ'.byteindex('')  #=> 6
'じゅげむじゅげむ'.byterindex('') #=> 18

String#bytesplice

Feature #18598: Add String#bytesplice - Ruby master - Ruby Issue Tracking System

String#bytesplice が追加された。 文字列のバイト位置の文字を置換する。

s = 'abcdefg'
s.bytesplice(3, 3, '12345')  #=> "12345"
# 'def' が '12345' に置換される
s  #=> "abc12345g"
s = 'あいうえお'
s.bytesplice(3, 3, '12345')  #=> "12345"
# 'い' が '12345' に置換される
s  #=> "あ12345うえお"

マルチバイト文字の場合は文字境界にあわないとエラーになる。

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 が 非推奨になり、3.3 で削除される予定になった。

-w つきで実行すると警告が出る。

% 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

Encoding#replicate なんて使ったことないから、何のために存在していたのかわかってない。

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 と Emoji 15.0 に対応した。Ruby 3.1 は Unicode 13.0.0 と Emoji 13.0 だった。

Ruby 3.1

'😀🫠😇🫨'.inspect  #=> "😀\u{1FAE0}😇\u{1FAE8}"

Ruby 3.2

'😀🫠😇🫨'.inspect  #=> "😀🫠😇🫨"