Skip to content

Instantly share code, notes, and snippets.

@jaredcwhite
Last active April 18, 2024 00:37
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 jaredcwhite/932b4fdcfb86bd2e531caf23f6659045 to your computer and use it in GitHub Desktop.
Save jaredcwhite/932b4fdcfb86bd2e531caf23f6659045 to your computer and use it in GitHub Desktop.
Truncating in the middle of a Ruby string
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
@jaredcwhite
Copy link
Author

jaredcwhite commented Apr 18, 2024

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