Last active
August 29, 2015 14:12
-
-
Save boone/9cd3ae6c80d3c816c11d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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ü" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment