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.scan
with a regular expression to break the string where you wish. Try somenthing like:
def magic_method(string_x)
splits = string_x.scan(/(.{0,9})(.*?)(.{0,9}$)/)[0]
splits[1] = "..." if splits[1].length > 3
splits.join
end
Explanation:
Supose string_a = "I'm a very long long long string"
; string_b = "A small test string"
; and string_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"
for string_a
; "A small t"
for string_b
and "tiny"
for string_c
.(.{0,9}$)
try to catch the last 9 or less characters and the end of string ($
). Ex."ng string"
for string_a
; "st string"
for string_b
and ""
for string_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"
for string_a
, "e"
for string_b
and ""
for string_c
Than we check if the middle group is greater than 3 characters, if so, we replace with "..."
. This will only happen on string_a
. Here we wouldn't like to make string_b
longer, replacing "e"
with "..."
resulting in "A simple t...st string"
.
Finally join the groups (array elements) into a single string with Array.join