String#center
str.center(width, padstr = ' ') -> string The .center method pads a string to a specified width, placing the original string in the center of the padded result. By default, it uses spaces for padding, but you can specify any character or string. This is useful for formatting terminal output, creating ASCII art, or generating aligned text tables.
Centering is the most decorative of the alignment helpers, but it still has practical uses. Headers, banners, and simple boxes become easier to scan when the text is balanced in the available width. When the width is odd, Ruby gives the extra character to the right, so the result stays predictable.
Syntax
str.center(width) # Pad with spaces (default)
str.center(width, padstr) # Pad with custom string
Parameters
| Parameter | Type | Description |
|---|---|---|
width | Integer | The total width of the resulting padded string |
padstr | String | The string to use for padding (default is space) |
Worked examples
The examples below show center applied to terminal formatting, headers, and tables. Each one builds on the idea of balancing text within a fixed width, starting with the simplest case and adding customisation as we go.
Example 1: Basic centering with spaces
text = "Ruby"
puts text.center(10)
# Output: " Ruby "
When the total width is larger than the string, Ruby distributes the padding equally on both sides. If the difference is odd, the right side gets one extra character.
That rule keeps the result stable across runs, which matters when you are formatting headings or building small text layouts. The method is simple, but the predictable padding makes it easier to line up labels without hand-counting spaces.
puts "Hi".center(10) # " Hi "
puts "Hello".center(10) # " Hello " (extra space on right)
puts "Ruby".center(10) # " Ruby "
Custom padding characters let you style centered text with borders, dividers, or decorative patterns. You can use single characters for clean lines or multi-character strings for more elaborate formatting, such as dotted separators or star-bordered banners. The padding character replaces the default space on both sides of the text.
Example 2: Using custom padding characters
puts "Ruby".center(10, "*") # "***Ruby***"
puts "Hi".center(10, "-") # "----Hi----"
puts "X".center(5, "=") # "==X=="
You can use multi-character strings for padding, which creates a repeating pattern around the centered text. Ruby applies the padding string character by character from left to right, so partial repetitions at the edges are possible when the total padding length is not an exact multiple of the pad string:
puts "Yo".center(10, "._.") # "._.Yo._.."
Multi-character padding is handy when you want the centered result to look decorative rather than plain. It works best when you are formatting headers or boxes, not when the text needs to align with data below it. For alignment-sensitive output, stick with single-character padding to avoid uneven edges.
Example 3: Centering in terminal output
title = "Welcome"
puts "+" + "-" * 20 + "+"
puts "|" + title.center(20) + "|"
puts "+" + "-" * 20 + "+"
# Output:
#+--------------------+
#| Welcome |
#+--------------------+
ASCII headers made with center are a lightweight alternative to dedicated formatting libraries. A small helper function that wraps center can produce consistent banners across your application without pulling in a gem dependency. The helper also centralises the width and border character choices, making global style changes trivial.
Example 4: Creating ASCII headers
def banner(text, width = 40)
border = "*" * width
puts border
puts text.center(width)
puts border
end
banner("Hello, World!")
# ****************************************
# Hello, World!
# ****************************************
The no-op behaviour when the target width is smaller than the string makes center safe to use in loops and dynamic layouts. You never risk truncation or an error, just a string that fills or exceeds the allotted space without any side effects.
Example 5: When width is less than string length
If the specified width is less than or equal to the string’s length, Ruby returns the original string unchanged.
puts "Ruby".center(2) # "Ruby" (no padding needed)
puts "Ruby".center(4) # "Ruby" (exact fit)
That behavior keeps center safe to use in formatting code where the width may vary. When the text already fills the target width, Ruby simply leaves it alone instead of trimming or wrapping it.
The next example demonstrates another aspect of this Ruby method in practice, showing different input types, edge cases, and usage patterns that are worth understanding before you use it in production code.
Common patterns
Building formatted tables
headers = ["Name", "Age", "City"]
data = [["Alice", "30", "London"], ["Bob", "25", "Paris"]]
width = 20
puts headers.map { |h| h.center(width) }.join(" | ")
puts "-" * (width * 3 + 4)
data.each do |row|
puts row.map { |cell| cell.center(width) }.join(" | ")
end
# Output:
# Name | Age | City
# ------------------------------------------------------------
# Alice | 30 | London
# Bob | 25 | Paris
Centered boxes are a simple way to draw attention to a message in terminal output. The pattern of borders plus centered text is reusable and easy to adjust for different widths or border characters without rewriting the layout logic.
Creating centered boxes
def centered_box(text, width = 40)
inner_width = width - 2
padded = text.center(inner_width)
"+" + "-" * inner_width + "+"
"|" + padded + "|"
"+" + "-" * inner_width + "+"
end
puts centered_box("IMPORTANT")
puts centered_box("Click Here")
# +--------------------------------------+
# | IMPORTANT |
# +--------------------------------------+
# | Click Here |
# +--------------------------------------+
Using center with a zero-padding character creates a distinctive visual effect for numbers. This is more decorative than practical for most use cases, but it demonstrates the flexibility of the second argument.
Number formatting
numbers = [1, 22, 333, 4444]
numbers.each do |num|
puts num.to_s.center(10, "0")
end
# Output:
# 0000010000
# 0000022000
# 0000333000
# 0004444000
center handles edge cases like empty strings and Unicode characters gracefully. The method counts characters, not bytes, so multibyte characters are padded correctly without manual width calculations or worrying about encoding details. The only case that raises an error is passing an empty padding string.
Edge cases
Empty strings and special characters
puts "".center(5) # " "
puts " ".center(5) # " " (single space becomes 5)
puts "\t".center(5) # tabs also pad correctly
puts "日本語".center(10) # " 日本語 " (Unicode works)
Passing an empty string as the padding character raises an ArgumentError because Ruby cannot pad with zero-width fill. This is the only case where center raises an exception rather than returning a result, so it is worth handling explicitly if the pad string comes from user input.
Padding with empty string
puts "Ruby".center(10, "") # Raises ArgumentError: zero width padding
Use center when the goal is visual balance rather than strict column alignment. It works well for headings and labels, but if the text needs to line up with data below it, ljust or rjust is usually the better fit.
See Also
- String#concat — Concatenate strings together
- String#slice — Extract substrings by index or range
- String#split — Split strings by delimiter