52
51

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2013-03-10

古くは弾さんのエントリにもある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]

参考

52
51
0

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
52
51

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?