LoginSignup
25
17

More than 5 years have passed since last update.

Rubyの文字数、バイト数取得について

Last updated at Posted at 2014-06-18

Rubyの文字数、バイト数取得について

文字数の取得は String#size/length メソッド

String#size , String#length を利用します。
http://docs.ruby-lang.org/ja/2.0.0/method/String/i/size.html

puts "h".size      # => 1
puts "h".length    # => 1
puts "あ".size     # => 1
puts "あ".length   # => 1

ただし、 Ruby1.8 の場合は String#size/length メソッドは
後述の String#bytesize と同様の結果を返却します。

バイト数の取得は String#bytesize メソッド

String#bytesize を利用します。

puts "h".bytesize  # => 1
puts "あ".bytesize # => 3
puts "h".encode("EUC-JP").bytesize  # => 1
puts "あ".encode("EUC-JP").bytesize # => 2

バイト数の取得 番外編

※コメント欄にて cielavenirさん から教えて頂いた内容(2014/06/26)。ありがとうございます。

Ruby1.9以上でも、ソースの先頭に#coding:ASCII-8BITと記述することでsizeをbytesizeと同義にすることが可能

#coding:ASCII-8BIT

puts "h".size      # => 1
puts "h".length    # => 1
puts "あ".size     # => 3
puts "あ".length   # => 3
25
17
2

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
25
17