Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active December 12, 2017 04:48
Show Gist options
  • Save komasaru/61321482c2dc8ed2b3168209e510b76d to your computer and use it in GitHub Desktop.
Save komasaru/61321482c2dc8ed2b3168209e510b76d to your computer and use it in GitHub Desktop.
Ruby script to truncate string, including multi-byte characters.
#! /usr/local/bin/ruby
#**************************************************************
# 全角文字を2byte換算し、指定バイトで切り捨て(省略文字設定可)
# ※正確には、「全角文字」ではなく1byte超の文字
#**************************************************************
class String
def trunc(trunc_at, om = "")
om_size = (om.bytesize - om.size) / 2 + om.size
if size == bytesize
return size <= trunc_at ? self : "#{self[0, trunc_at - om_size]}#{om}"
end
return self if (self.bytesize - self.size) / 2 + self.size <= trunc_at
size.times do |i|
str_size = (self[0..i].bytesize - self[0..i].size) / 2 + self[0..i].size
case
when str_size < trunc_at - om_size; next
when str_size == trunc_at - om_size; return "#{self[0..i]}#{om}"
else; return "#{self[0..(i - 1)]}#{om}"
end
end
return self
end
end
str = "abcdefg"
puts "str = #{str}"
puts "str.trunc(5) = #{str.trunc(5)}"
puts "str.trunc(6) = #{str.trunc(6)}"
puts "str.trunc(7) = #{str.trunc(7)}"
puts "str.trunc(8) = #{str.trunc(8)}"
puts "str.trunc(5, \"...\") = #{str.trunc(5, "...")}"
puts "str.trunc(6, \"...\") = #{str.trunc(6, "...")}"
puts "str.trunc(7, \"...\") = #{str.trunc(7, "...")}"
puts "str.trunc(8, \"...\") = #{str.trunc(8, "...")}"
puts
str = "AあBいCうDえEお"
puts "str = #{str}"
puts "str.trunc(12) = #{str.trunc(12)}"
puts "str.trunc(13) = #{str.trunc(13)}"
puts "str.trunc(14) = #{str.trunc(14)}"
puts "str.trunc(15) = #{str.trunc(15)}"
puts "str.trunc(16) = #{str.trunc(16)}"
puts "str.trunc(12, \"...\") = #{str.trunc(12, "...")}"
puts "str.trunc(13, \"...\") = #{str.trunc(13, "...")}"
puts "str.trunc(14, \"...\") = #{str.trunc(14, "...")}"
puts "str.trunc(15, \"...\") = #{str.trunc(15, "...")}"
puts "str.trunc(16, \"...\") = #{str.trunc(16, "...")}"
puts "str.trunc(12, \"(続く)\") = #{str.trunc(12, "(続く)")}"
puts "str.trunc(13, \"(続く)\") = #{str.trunc(13, "(続く)")}"
puts "str.trunc(14, \"(続く)\") = #{str.trunc(14, "(続く)")}"
puts "str.trunc(15, \"(続く)\") = #{str.trunc(15, "(続く)")}"
puts "str.trunc(16, \"(続く)\") = #{str.trunc(16, "(続く)")}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment