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] + "…"
  puts str
# => "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

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


2 thoughts on “How to trim a string and fill remaining space in Ruby

  1. 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

Your email address will not be published. Required fields are marked *