Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
51
Help us understand the problem. What is going on with this article?
@chezou

RubyでIntegerと文字を相互変換する

More than 5 years have passed since last update.

古くは弾さんのエントリにもあるchrとordのお話。
なお、Ruby1.9以降を前提にしています。1.8は多分挙動がだいぶ違うはず。

RubyとUnicodeのCodepointの話は、下記の記事がわかりやすくよくまとまっていています。

ポイント

  • ASCIIにない範囲の文字をchrするときは、encodingを指定すること
  • UnicodeのRangeは、0x0〜0x10FFFF (1114111)まで

サンプルコード

sample.rb
# ASCIIの変換
p "A".ord # => 65
p 65.chr  # => "A"
p "A".ord.chr # => "A"

# UTF-8の変換
p "文".ord # => 25991
# encodingを指定しないとUS-ASCIIの範囲で文字を返そうとする
p 25991.chr # RangeError: 25991 out of char range
p 25991.chr("UTF-8") # => "文"
p 25991.chr(Encoding::UTF_8) # => "文"

p 1114112.chr(Encoding::UTF_8) # RangeError: invalid codepoint 0x110000 in UTF-8

ちなみに、"\u{16進数}"でコードポイントに対応する文字が出せるんですね。

p 25991.to_s(16) # => "6587"
p "\u{6587}" # => "文"

文字列を取得したら.each_codepointを使うと数値列に変換するのが良いでしょう。

"あいうえお".each_codepoint.to_a #=> [12354, 12356, 12358, 12360, 12362]

参考

51
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
chezou
Rubyのコミュニティをやりながら、データ分析や機械学習が好きな人。最近はPythonやRも触ります。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
51
Help us understand the problem. What is going on with this article?