How can I center truncate a string?

Viewed 4088

Does anybody have any code handy that center truncates a string in Ruby on Rails?

Something like this: Ex: "Hello World, how are you?" => "Hel...you?"

13 Answers

Modified rails version that only truncated from the middle

def middle_truncate(str, total: 30, lead: 15, trail: 15)
  str.truncate(total, omission: "#{str.first(lead)}...#{str.last(trail)}")
end

A combination of Benjamin Sullivan's and khelll's answers. Uses built-in Rails stuff and lets you define edge length.

With String#truncate, I don't think there's a need to define minimum length at all. This solution automatically shortens the string if the shortened version is shorter than the input string.

def ellipsize(string, edge_length, separator: '…')
  string.truncate(
    edge_length * 2 + separator.size, omission: "#{separator}#{string.last(edge_length)}"
  )
end

Here's my version that lets you specify the maximum length instead, so, you can ensure that a string doesn't exceed the required length:

class String
    def truncate(maximum_length = 3, separator = '…')
        return '' if maximum_length.zero?
        return self if self.length <= maximum_length

        middle_length = self.length - maximum_length + separator.length
        edges_length = (self.length - middle_length) / 2.0
        left_length = edges_length.ceil
        right_length = edges_length.floor

        left_string = left_length.zero? ? '' : self[0, left_length]
        right_string = right_length.zero? ? '' : self[-right_length, right_length]

        return "#{left_string}#{separator}#{right_string}"
    end
end
'123456'.truncate(0) # ""
'123456'.truncate(1) # "…"
'123456'.truncate(2) # "1…"
'123456'.truncate(3) # "1…6"
'123456'.truncate(4) # "12…6"
'123456'.truncate(5) # "12…56"
'123456'.truncate(6) # "123456"
'123456'.truncate(7) # "123456"
Related