Ruby Method of the Day - String.ljust

Posted by Kelly McCauley on Sep 18, 2007

Signature

string.ljust(length)                  #=> new_string
string.ljust(length, padding_string)  #=> new_string

string.ljust(length) left justifies string to the given length. If length is greater than the length of string then a new string is returned that is right padded to length with spaces, the default, or with padding_string. If length is less than or equal to the length of string, then string.ljust(length) returns a new string that is equal to string and no padding or truncating occurs.

Examples

1
2
3
4
'foo'.ljust(10)     #=> "foo       "
'foo'.ljust(10,'x') #=> "fooxxxxxxx"
'foo'.ljust(2)      #=> "foo"
'foo'.ljust(2,'x')  #=> "foo"

Documentation Reference

www.ruby-doc.org : String.ljust