Truncate a UTF-8 string at character boundary in Ruby 1.8

Language: Ruby

# For more on $KCODE, see
#   http://blog.grayproductions.net/articles/the_kcode_variable_and_jcode_library
$KCODE = 'u'

def truncate(str, length)
  str.match(/.{0,#{length}}/m).to_s
end

p truncate("åéîøü", 3) # => "åéî"
Reveal More
Added about 2 years ago by Devo_normal gbuesing