instance method
String#center
(::int width, ?::string pad_string) -> ::String
center(size, pad_string = ' ') → new_string
string.c
View on GitHub ↗
static VALUE
rb_str_center(int argc, VALUE *argv, VALUE str)
{
return rb_str_justify(argc, argv, str, 'c');
}
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
-
3.0
-
The following methods now return or yield
Stringinstances instead of subclass instances when called on subclass instances: [Bug #10845]
-