How to center a string in Ruby with the center() method

Overview

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.

Syntax

str.center(width)

Parameters

  • str: the string you want to center.

  • width: the width in which you want to center the string.

Return value

center() returns a new string.

Code example

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.

Free Resources