Skip to content
instance method

String#center

(::int width, ?::string pad_string) -> ::String
center(size, pad_string = ' ') → new_string

Returns a centered copy of self.

If integer argument size is greater than the size (in characters) of self, returns a new string of length size that is a copy of self, centered and padded on one or both ends with pad_string:

Example
'hello'.center(6)             # => "hello "               # Padded on one end.
'hello'.center(10)            # => "  hello   "           # Padded on both ends.
'hello'.center(20, '-|')      # => "-|-|-|-hello-|-|-|-|" # Some padding repeated.
'hello'.center(10, 'abcdefg') # => "abhelloabc"           # Some padding not used.
'  hello  '.center(13)        # => "    hello    "
'Привет'.center(10)           # => "  Привет  "
'こんにちは'.center(10)         # => "  こんにちは   "      # Multi-byte characters.

If size is less than or equal to the size of self, returns an unpadded copy of self:

Example
'hello'.center(5)   # => "hello"
'hello'.center(-10) # => "hello"

Related: see Converting to New String.

Ruby version changes

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