method

center

v1_8_7_72 - Show latest stable - Class: String
center(...)
public

If integer is greater than the length of str, returns a new String of length integer with str centered and padded with padstr; otherwise, returns str.

   "hello".center(4)         #=> "hello"
   "hello".center(20)        #=> "       hello        "
   "hello".center(20, '123') #=> "1231231hello12312312"

1Note

Odd Number of padding characters

WedTM ยท Feb 11, 2010

In the case of an odd number of empty spaces in a length, Ruby will append the extra character to the right-hand side of the string.

Example:

irb(main):002:0> "Hello".center(10,"-")
=> "--Hello---"