Let string_a = "I'm a very long long long string"
Is there a method in Ruby that truncates a string something like this?:
magic_method(string_a) # => "I'm a ver...ng string"
In Rails I can do: truncate(string_a) but only the first part is returned.
You can try the method
String.scanwith a regular expression to break the string where you wish. Try somenthing like:Explanation:
Supose
string_a = "I'm a very long long long string";string_b = "A small test string"; andstring_c = "tiny". First split the string within 3 groups.(.{0,9})try to catch the first 9 or less characters. Ex."I'm a ver"forstring_a;"A small t"forstring_band"tiny"forstring_c.(.{0,9}$)try to catch the last 9 or less characters and the end of string ($). Ex."ng string"forstring_a;"st string"forstring_band""forstring_c;(.*?)try to catch what is left over. This only works because of the?that makes this regular expression not greedy (otherwise it would get the rest of the string, lefting nothing to the last group. Ex:"y long long lo"forstring_a,"e"forstring_band""forstring_cThan we check if the middle group is greater than 3 characters, if so, we replace with
"...". This will only happen onstring_a. Here we wouldn’t like to makestring_blonger, replacing"e"with"..."resulting in"A simple t...st string".Finally join the groups (array elements) into a single string with
Array.join