Randy Girard

How to trim a string and fill remaining space in Ruby

So I needed a way to take a string, and depending on its size, shorten it and fill the remaining space with some arbitrary sequence of characters. Ljust would work, except for the fact that it will fill a string up to a given length, but I only needed to do this when over a certain size. Here is an example:

str = "Somereallylongstring"
if str.length > 10
  puts str[0..7] + "…"
else
  puts str
end
# => "Somerea..."

This is the basic idea of what I wanted to do. I decide to make it cleaner and override the String class like so:

class String
  def lfill(len = self.length, fill = ".")
    tmp = self[0..(len – 3)] + "..." if self.length – 3 > len
    return tmp || self
  end
end

nstr = "Somereallylongstring"
puts str.lfill(10)
#=> "Somerea..."