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_strParameters: 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:
#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) |
Output:
String
Methods
Example 2:
#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') |
Output:
45Ruby456 789String Class789
Recommended Posts:
- Ruby | String =~ Method
- Ruby | String << Method
- Ruby | String == method
- Ruby | String <=> Method
- Ruby | String + Method
- Ruby | String hex Method
- Ruby | String eql? Method
- Ruby | String === Method
- Ruby | String chr Method
- Ruby | String * Method
- Ruby | String end_with? Method
- Ruby | String hash method
- Ruby | String inspect Method
- Ruby | String gsub! Method
- Ruby | String getbyte Method
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.



