Skip to content

Instantly share code, notes, and snippets.

@kyohei8
Created November 19, 2013 07:00
Show Gist options
  • Save kyohei8/7541358 to your computer and use it in GitHub Desktop.
Save kyohei8/7541358 to your computer and use it in GitHub Desktop.
Operation of multi-byte string in Ruby Rubyで全角文字列を調べる 1. 全角を2,半角を1とした、文字列の長さを導出 2. 全角文字の数
# 全角を2,半角を1とした、文字列の長さを導出
# @param string 文字列
def get_exact_size(string)
string.each_char.map{|c| c.bytesize == 1 ? 1 : 2}.reduce(0, &:+)
end
get_exact_size "aあ" #=>3
get_exact_size "('aa漢字')" #=>10
# 全角文字をカウント
# @param string 文字列
def count_multi_byte(string)
string.each_char.map{|c| c.bytesize == 1 ? 0 : 1}.reduce(0, &:+) unless string.ascii_only?
end
count_multi_byte "aあ" #=>1
count_multi_byte "('aa漢字')" #=>2
# クラスを再オープンする場合
class String
def exact_size
self.each_char.map{|c| c.bytesize == 1 ? 1 : 2}.reduce(0, &:+)
end
def count_multi_byte
self.each_char.map{|c| c.bytesize == 1 ? 0 : 1}.reduce(0, &:+) unless self.ascii_only?
end
end
"aあ".exact_size #=> 3
"aあ".count_multi_byte #=> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment