Alex
Alex

Reputation: 2076

Ruby: truncating a long string contained in another string

Let string_a = "I'm a string but this aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa is long."

How is it possible to detect the aaaa...aaa (the part without spaces that is very long) part and truncate it so that the result looks like (the rest of the string should look the same):

puts string_a # => "I'm a string but this aaa....aaa is long."

I use this method to truncate:

  def truncate_string(string_x)
    splits = string_x.scan(/(.{0,9})(.*?)(.{0,9}$)/)[0]
    splits[1] = "..." if splits[1].length > 3
    splits.join
  end

So running:

puts truncate_string("I'm a very long long long string") # => "I'm a ver...ng string"

The problem is detecting the 'aaaa...aaaa' and apply truncate_string to it.

First part of the solution? Detecting strings that are longer than N using regex?

Upvotes: 0

Views: 154

Answers (2)

christianblais
christianblais

Reputation: 2458

What about something like

string.gsub(/\S{10,}/) { |x| "#{x[0..3]}...#{x[-3..-1]}" }

where 10 is the maximum length of a word?

Upvotes: 2

phoet
phoet

Reputation: 18835

how do you like this?

s = "I'm a string but this aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa is long."
s.gsub(/(.* \w{3})\w{5,}(\w{3}.*)/, '\1...\2')
 => "I'm a string but this aaa...aaa is long." 

Upvotes: 1

Related Questions