Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

String#center

str.center(width, padstr=' ') → new_str

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

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

Ruby version changes

  1. 3.0
See also #casecmp? #chars #casecmp #chomp also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1