We can use the center()
method to center a string in Ruby. The center()
method centers a string in the specified width. If the specified width is greater than the string, center()
returns a new string with a length equal to the width.
str.center(width)
str
: the string you want to center.
width
: the width in which you want to center the string.
center()
returns a new string.
In the example below, we will create some strings and center them with the center()
method.
# create some strings str1 = "Hello" str2 = "Edpresso" str3 = "is" str4 = "the" str5 = "best" # center strings a = str1.center(10) b = str2.center(7) c = str3.center(20) d = str4.center(5) e = str5.center(5) # print returned values puts a puts b puts c puts d puts e
NOTE: When the width is less than the length of the original string, the
center()
method returns the original string.
RELATED TAGS
CONTRIBUTOR
View all Courses