I want to truncate a string as follows:
input:
string = \"abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa ffffdffffdffffdffffddd\"
Similar to what some others have suggested here, you can use Rails' #truncate method and use a custom omission that is actually the last part of your string:
string = "abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa ffffdffffdffffdffffffffd"
truncate(string, length: 37, omission: "...#{string[-5, 5]}")
# => "abcd asfsa sadfsaf safsdaf aa...ffffffffd"
Exactly what you wanted.
You might want to wrap this up in a custom method called something like truncate_middle
that does some fancy footwork for you:
# Truncate the given string but show the last five characters at the end.
#
def truncate_middle( string, options = {} )
options[:omission] = "...#{string[-5, 5]}" # Use last 5 chars of string.
truncate( string, options )
end
And then just call it like so:
string = "abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa ffffdffffdffffdffffffffd"
truncate_middle( string, length: 37 )
# => "abcd asfsa sadfsaf safsdaf aa...ffffffffd"
Boom!
Thanks for asking about this. I think it's a useful way to show a snippet of a longer piece of text.