Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
String#center
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 both ends with pad_string:
Example
'hello'.center(10) # => " hello " ' hello'.center(10) # => " hello " 'hello'.center(10, 'ab') # => "abhelloaba" 'тест'.center(10) # => " тест " 'こんにちは'.center(10) # => " こんにちは "
If size is not greater than the size of self, returns a copy of self:
Example
'hello'.center(5) # => "hello" 'hello'.center(1) # => "hello"
Related: String#ljust, String#rjust.
Ruby version changes
-
3.0
-
The following methods now return or yield
Stringinstances instead of subclass instances when called on subclass instances: [Bug #10845]
-