Ruby Method of the Day - String.center

Posted by Kelly McCauley on Sep 20, 2007

Signature

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

The String.center method is in the same family of methods as String.ljust and String.rjust.

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

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
'foo'.center(10)      #=> "   foo    "
'foo'.center(10,'x')  #=> "xxxfooxxxx"
'foo'.center(2)       #=> "foo"
'foo'.center(2,'x')   #=> "foo"

l = 'left'            #=> "left"
r = 'right'           #=> "right"
c = 'center'          #=> "center"
l.ljust(8) + c.center(8) + r.rjust(8)   #=> "left     center    right"

text = <<-'END'
Lorem ipsum dolor sit amet, consectetuer
adipiscing elit. Ut ac nulla.  Duis sed est.
Praesent at dui et velit tempor cursus.
Morbi purus tortor, tempus tincidunt,
placerat sit amet, dignissim quis, nulla.
Duis ipsum. Proin fringilla.
END

# Prints out each line of the paragraph above, centered.
text.each_line {|l| puts l.chomp.center(50) }

Documentation Reference

www.ruby-doc.org : String.center