5
5

More than 5 years have passed since last update.

ある文字列を特定のEncodingで指定バイト数に収まる長さで切り出す

Last updated at Posted at 2013-10-07

こんな感じ?
もっと楽な方法ないかな?

truncate_with_encoding.rb
  def truncate_with_encoding(string, target_encoding, max_byte)
    original_encoding = string.encoding

    encoded_string = string.encode(target_encoding)
    result = ""
    encoded_string.each_char {|c|
      total_bytes = result.bytesize + c.bytesize
      result << c if total_bytes <= max_byte
    }

    result.encode(original_encoding)
  end

実行結果

truncate_with_encoding("abcあいう", Encoding::SJIS, 6)
# => "abcあ"
5
5
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
5
5