Ruby Method of the Day - String.rjust

Posted by Kelly McCauley on Sep 19, 2007

Signature

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

String.rjust is the counter justification method to String.ljust. string.rjust(length) right justifies string to the given length. If length is greater than the length of string then a new string is returned that is left 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.rjust(length) returns a new string that is equal to string and no padding or truncating occurs.

Examples

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

Documentation Reference

www.ruby-doc.org : String.rjust