String#rjust
str.rjust(width, padstr = ' ') -> string The .rjust method pads a string to a specified width on the left side, placing the original string on the right. By default, it uses spaces for padding, but you can specify any character or string. This is useful for formatting numeric output, creating fixed-width tables, or aligning text to the right in terminal applications.
Right-justified output is particularly helpful when the values themselves should line up visually, such as numbers in a report or totals in a column. Right alignment makes it easier to compare lengths at a glance, which is why you often see it in financial, log, and status output.
What makes rjust useful is how it solves a common layout problem cleanly. Instead of counting spaces by hand, you give Ruby the width you want and let it produce the padding for you.
Syntax
str.rjust(width) # Pad with spaces (default)
str.rjust(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) |
The width parameter sets the total output length including both the original string and the added padding, while padstr controls what fills the space on the left side. Together they give you full control over both column width and visual style with only two arguments.
worked examples
Example 1: Basic right-justification with spaces
text = "Ruby"
puts text.rjust(10)
# Output: " Ruby"
When the total width is larger than the string, Ruby adds padding to the left side. The amount of padding is the difference between the target width and the string’s own length, so shorter strings receive more space while longer strings start closer to the right edge. This simple arithmetic means you get predictable column alignment without any manual space counting or formatting logic.
puts "Hi".rjust(10) # " Hi"
puts "Hello".rjust(10) # " Hello"
puts "Ruby".rjust(10) # " Ruby"
Each call in the example above pads a different string to the same width of ten characters. Because the strings themselves have different lengths, the amount of leading space varies, but the total output width stays constant. This consistency is what makes rjust useful for columnar output: every row occupies the same horizontal space regardless of the data it contains, so columns stay aligned even when values span a wide range of widths.
Example 2: Using custom padding characters
puts "Ruby".rjust(10, "*") # "******Ruby"
puts "Hi".rjust(10, "-") # "--------Hi"
puts "X".rjust(5, "=") # "====X"
Custom padding characters are not limited to single characters. You can use multi-character strings for padding, and Ruby will repeat the fill pattern as many times as needed to reach the target width, then trim the final repetition if it would overshoot. This trimming means the padded result always ends exactly at the requested width, even if the fill pattern does not divide cleanly into the space available.
puts "Yo".rjust(10, "._.") # "._._._._.Yo"
Custom padding strings are useful when you want a decorative or repeated fill character. Ruby repeats the pattern as needed, then trims it to the exact width. Because the padding string is applied as a repeating cycle rather than being inserted as a single block, you get a uniform visual rhythm across the left side of the output. This works especially well for status bars, progress indicators, and any output where the fill pattern carries meaning beyond simple spacing.
example 3: creating formatted numeric tables
numbers = [7, 42, 128, 1024, 4096]
numbers.each do |num|
puts num.to_s.rjust(5)
end
# Output:
# 7
# 42
# 128
# 1024
# 4096
Numeric columns are one of the cleanest uses for rjust. The output stays readable because shorter numbers get enough leading space to line up with the longer values below them. This pattern is especially valuable in log files and reports where the numbers change on each run: the alignment stays consistent even as values grow or shrink, and the reader’s eye can scan down the column without adjusting to a shifting left edge.
example 4: right-aligning variable-width data
labels = ["Name:", "Email:", "Status:"]
values = ["john", "john@example.com", "active"]
labels.zip(values).each do |label, value|
puts "#{value.rjust(20)}: #{label}"
end
# Output:
# john: Name:
# john@example.com: Email:
# active: Status:
This example shows that rjust is not limited to numbers. Any value that should sit flush against the right edge can use the same method.
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".rjust(2) # "Ruby" (no padding needed)
puts "Ruby".rjust(4) # "Ruby" (exact fit)
That behavior makes the method easy to use in code that calculates widths dynamically. If the target width turns out to be too small, the string still comes back safely without raising an exception or truncating data. This is especially helpful when you are computing the width from the longest value in a column: you can pass the same width to every row and trust that shorter values will be padded while values that happen to exceed the computed width will simply pass through untouched.
common patterns
Building CLI tables with right-aligned columns
data = [
["Item", "Qty", "Price"],
["Apple", "5", "2.50"],
["Banana", "12", "1.80"],
["Cherry", "100", "0.50"]
]
# Right-align numeric columns
data.each do |row|
puts row[0].ljust(10) + row[1].rjust(5) + row[2].rjust(10)
end
# Output:
# Item | 5| 2.50
# Banana | 12| 1.80
# Cherry | 100| 0.50
This kind of tabular formatting is why rjust shows up in command-line tools so often. It keeps numeric columns visually stable without needing a formatting library for simple output. Combined with ljust for left-aligned columns, you get a complete lightweight formatting system that handles the most common table layouts without pulling in a dependency. The trade-off is that you need to know the column widths ahead of time, which usually means scanning the data once to find the maximum width before printing.
Formatting file sizes
sizes = [512, 1024, 1536, 2048, 4096]
sizes.each do |bytes|
puts "#{bytes.to_s.rjust(6)} bytes"
end
# Output:
# 512 bytes
# 1024 bytes
# 1536 bytes
# 2048 bytes
# 4096 bytes
The byte-count example is another good fit because each row has the same kind of data but different widths. Right alignment makes the numbers easy to compare without extra parsing. This pattern generalises to any numeric column where the values share a unit: file sizes, durations in seconds, percentages, or monetary amounts. As long as the unit label sits to the right of the number, the digits will line up and the reader can compare magnitudes at a glance.
Creating indented code blocks
code = ["def hello", " puts 'World'", "end"]
code.each do |line|
puts line.rjust(line.length + 4)
end
# Output:
# def hello
# puts 'World'
# end
Even indentation can use rjust when the goal is to shift a line right by a consistent amount. The example is a little playful, but it shows that the method only cares about width, not meaning. In practice, you are more likely to use rjust for numeric and tabular data than for indenting code, but the principle is the same: give Ruby a target width and a fill string, and it produces predictable padded output every time.
edge cases
Empty strings and special characters
puts "".rjust(5) # " "
puts " ".rjust(5) # " " (single space becomes 5)
puts "\t".rjust(5) # tabs also pad correctly
puts "日本語".rjust(10) # " 日本語" (Unicode works)
Unicode text still counts toward the string’s length, so rjust can pad it just like ASCII text. That keeps the method predictable in multilingual output. Ruby measures string length in characters, not bytes, which means a string like “日本語” (three characters) pads to a visual width of three even if the underlying UTF-8 encoding occupies more bytes in memory. This character-aware measurement is the same one used by String#length and String#size, so padding calculations stay consistent with all other length-based operations.
Padding with empty string
Providing an empty string as the padding character produces an ArgumentError because Ruby cannot fill the requested space with a zero-width pad. The error message reads “zero width padding” and is raised before any work is done, so the original string is never modified even in the error case.
puts "Ruby".rjust(10, "") # Raises ArgumentError: zero width padding
Passing an empty string as the padding argument makes no sense because there is nothing to fill the gap with, so Ruby raises an ArgumentError immediately. This is a guard against a logical mistake rather than a runtime limitation. The same rule applies to ljust and center, which share the same padding machinery. If you ever need to pad with an empty string, you almost certainly want to reconsider the design.
Negative width
puts "Ruby".rjust(-5) # Raises ArgumentError: negative string size
A negative width is conceptually meaningless when the goal is to produce a string of a certain total length, so Ruby treats it as an error rather than silently clamping to zero or wrapping around. This is consistent with how ljust and center handle negative arguments. If your code computes widths dynamically and the result might dip below zero, guard the call with [computed_width, 0].max to avoid the exception.
In practice, rjust pairs well with ljust and center because each one expresses a different layout intent. Choosing the alignment method directly makes the output code read like a small formatting rule instead of a pile of string math.
See Also
- String#ljust — Pad a string on the right (left-justify)
- String#center — Center a string by padding on both sides
- String#slice — Extract substrings by index or range