How to force Ruby string to n characters

Ruby supports using format strings, like many other languages:

[11] (pry) main: 0> '%3.3s' % 'f'
=> "  f"
[12] (pry) main: 0> '%3.3s' % 'foo'
=> "foo"
[13] (pry) main: 0> '%3.3s' % 'foobar'
=> "foo"

If you want to pad on the right, use a - in the format string:

[14] (pry) main: 0> '%-3.3s' % 'f'
=> "f  "
[15] (pry) main: 0> '%-3.3s' % 'foo'
=> "foo"
[16] (pry) main: 0> '%-3.3s' % 'foobar'
=> "foo"

You could also use printf or sprintf, but I prefer the more generic %, which is like sprintf.

From the sprintf docs:

  s   | Argument is a string to be substituted.  If the format
      | sequence contains a precision, at most that many characters
      | will be copied.

and:

-        | all           | Left-justify the result of this conversion.

What if I want to pad not with spaces but with some other character?

The underlying Ruby code is written in C, and it's hard-coded to use ' ' as the pad character, so that's not possible directly, unless you want to modify the source, recompile your Ruby, and live with a one-off version of the language. Instead, you can do something like:

[17] (pry) main: 0> ('%-3.3s' % 'f').gsub(' ', '.')
=> "f.."

This gets a lot more complicated than a simple gsub though. Often it's better to adjust the string without using format strings if you need to supply special characters. Format strings are very powerful but they're not totally flexible.

Otherwise, I'd go with something like @steenslag's solution, which is the basis for rolling your own. You lose the ability to use format strings and have to rely on concatenating your strings or something similar to get columnar output, but it will also work.


To make a string a fixed length shorter:

  str_var.slice(0..10) # starts at the first letter

To make a string a fixed length longer:

  str_var.ljust(10, ' ')

They could be combined into something like:

  (str_var.length > 10) ? str_var.slice(1..10) : str_var.ljust(10, ' ')

Where str_var is, of course, your string


class String
  def fix(size, padstr=' ')
    self[0...size].rjust(size, padstr) #or ljust
  end
end

p 'lettersletters'.fix(9) #=> "lettersle"
p 'letters'.fix(10, '.')  #=> "...letters"

Combines the slice method (the []) with rjust.


For a pure Ruby one liner you might do this:

(str + ' ' * length)[0,length]

Which will yield:

str = "Hello"
length = 10
=> "Hello     "

or:

str = "Hello"
length = 2
=> "He"