Open In App

Ruby | String center() method

Last Updated : 07 Jan, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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:




#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

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads