Skip to content

Instantly share code, notes, and snippets.

@boone
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boone/9cd3ae6c80d3c816c11d to your computer and use it in GitHub Desktop.
Save boone/9cd3ae6c80d3c816c11d to your computer and use it in GitHub Desktop.
# truncate string by byte limit
#
# str - String
# limit - Maximum number of bytes
#
# Returns a String
def limit_string(str, limit)
limited_string = ""
str.each_char do |c|
break if limited_string.bytesize + c.bytesize > limit
limited_string += c
end
limited_string
end
limit_string("The biggest molecule", 20) # "The biggest molecule"
limit_string("Am größten Molekül", 20) # "Am größten Molekü"
@InfraRuby
Copy link

def limit_string(s, n)
  i = 0
  s.each_char do |c|
    j = i + c.bytesize
    break if j > n
    i = j
  end
  return s.byteslice(0, i)
end

limit_string("The biggest molecule", 20) # "The biggest molecule"
limit_string("Am größten Molekül", 20)   # "Am größten Molekü"

@boone
Copy link
Author

boone commented Jan 7, 2015

@InfraRuby, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment