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
 
str = "Somereallylongstring"
puts str.lfill(10)
 
#=> "Somerea..."

 

Tags: , , , ,

2 Responses to “How to trim a string and fill remaining space in Ruby”

  1. Coren Says:

    You should take a look at StringIO#truncate

  2. Randy Says:

    Thanks for the reply.

    I think truncate would only help out in the situation where I am using [0..(len - 3)], because I also need the functionality to append some filler text. Unless I’m missing something.

    Good find though!

Leave a Reply