こんな感じ?
もっと楽な方法ないかな?
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あ"