Last active
April 18, 2024 00:37
-
-
Save jaredcwhite/932b4fdcfb86bd2e531caf23f6659045 to your computer and use it in GitHub Desktop.
Truncating in the middle of a Ruby string
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
class String | |
def middle_truncate(truncate_length = 30) | |
return self if length <= truncate_length + 2 | |
"#{self[..(truncate_length / 2)]}…#{self[-(truncate_length / 2)..]}" | |
end | |
end | |
puts "Well, this is a very long string and I hope I can see if it will truncate!".middle_truncate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run in browser: https://runruby.dev/gist/932b4fdcfb86bd2e531caf23f6659045