Ruby | String center() method

center is a String class method in Ruby which is used to centers the given string in width. If the specified width is greater than the length of the given string, then this method will return a new string of the specified width with the given string centered and padded otherwise it returns only given string.

Syntax:

str.center(width, padstr='')->new_str

Parameters: Here, str is the given string and width is the specified width used to center the string.



Returns: This method can either return a new modified string new_str or the same string.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

#ruby 2.3.1 
    
# Ruby program to demonstrate
# the center method
    
# Taking a string and
# using the method
puts "String".center(5)
puts "Methods".center(18)

chevron_right


Output:

String
     Methods

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#ruby 2.3.1 
    
# Ruby program to demonstrate
# the center method
    
# Taking a string and
# using the method
puts "Ruby".center(9, '456')
puts "String Class".center(18, '789')

chevron_right


Output:

45Ruby456
789String Class789


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.