Skip to content

Instantly share code, notes, and snippets.

@boone
Last active August 29, 2015 14:12
Show Gist options
  • 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ü"
@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