LoginSignup
0
0

More than 1 year has passed since last update.

Rubyで文字のUnicode(10進数表記)を取得する

Posted at

TL;DR

String.ord or String.unpack("U*")を使う

'あ'.ord          # 12354
'あ'.unpack("U*") # [12354]

ordとunpackの違い

返り値の型が違うので実装上は注意が必要です。
ordは最初の文字のUnicodeをIntで返しますが、unpackは1文字ずつのUnicodeをArrayで返します。

# 対象が1文字
'あ'.ord                  # 12345
'あ'.unpack("U*")         # [12354]

# 対象が複数文字
'あいうえお'.ord           # 12354
'あいうえお'.unpack("U*")  # [12354, 12356, 12358, 12360, 12362]

# ordを使うとちょっと複雑になる
'あいうえお'.chars.map{|c|c.ord} # [12354, 12356, 12358, 12360, 12362]

厳密な違いは公式リファレンスをご参照ください。

その他

公式リファレンスを読んでも何進数なのか、Unicode返してるのか等が明記されていなかったのでまとめてみました。
golangruneと同じ事ができるので書き換えの際などにご参照いただけると。
突然出てきたgolangのお話はこちらの記事がわかりやすかったので気になる方はご参照ください。
Goのruneを理解するためのUnicode知識

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0