String#ljust
str.ljust(width, padstr = ' ') -> string The .ljust method pads a string to a specified width on the right side, placing the original string on the left. By default, it uses spaces for padding, but you can specify any character or string. This is useful for formatting table columns, creating fixed-width output, or aligning text in terminal applications.
The method is most useful when the output is meant for a person rather than a parser. Tables, status lines, and quick command-line reports all become easier to scan when the labels line up. Because ljust leaves the original text first, it reads naturally in layouts where the important part should start at the left edge.
Syntax
str.ljust(width) # Pad with spaces (default)
str.ljust(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 controls how many characters the final string occupies, while padstr lets you choose what fills the extra space. If padstr is longer than needed, Ruby truncates it to fit; if it is empty, Ruby raises an ArgumentError. Knowing both parameters helps you pick the right padding for tables, logs, or any fixed-width output where alignment matters.
Worked Examples
Example 1: Basic left-justification with spaces
text = "Ruby"
puts text.ljust(10)
# Output: "Ruby "
When the total width is larger than the string, Ruby adds padding to the right side.
That simple rule keeps labels lined up without changing the visible content itself. It is especially useful when you want the important part of the text to stay on the left edge of a column or report. Each string below starts at the same position, which makes the output easy to scan in a terminal. Notice that the padding is always added to the right, never the left, so the original text stays exactly where you placed it.
puts "Hi".ljust(10) # "Hi "
puts "Hello".ljust(10) # "Hello "
puts "Ruby".ljust(10) # "Ruby "
Example 2: Using custom padding characters
Spaces are the default, but ljust accepts any padding string as its second argument. This is handy when you want a visual separator between columns or when a log format calls for dashes or dots instead of spaces. The padding character replaces the default space and is repeated until the total width is reached.
puts "Ruby".ljust(10, "*") # "Ruby******"
puts "Hi".ljust(10, "-") # "Hi--------"
puts "X".ljust(5, "=") # "X===="
A single padding character is the most common choice, but you are not limited to one character. The padstr argument can be any string, and Ruby repeats it as many times as needed to reach the target width. This makes the method flexible: you can use a dot for a table of contents, an underscore for a form field, or any pattern that fits the context.
puts "Yo".ljust(10, "._.") # "Yo._._._._."
Multi-character padding is less common, but it can make a column look intentionally styled. In practice, though, simple spaces or a single repeated character are usually easier to read. The repeating pattern from a multi-character pad string can also look uneven when the width is not a multiple of the pad string length, so most formatting code sticks with single characters.
Example 3: Creating formatted table columns
ljust really shines when you combine it with iteration. The next example builds a simple text table by left-justifying each cell to a fixed width, then joining columns with a separator.
data = [
["Name", "Age", "City"],
["Alice", "30", "London"],
["Bob", "25", "Paris"],
["Carolyn", "28", "Berlin"]
]
# Print table with left-justified columns
data.each do |row|
puts row.map { |cell| cell.ljust(10) }.join(" | ")
end
# Output:
# Name | Age | City
# ------------------------------------------------
# Alice | 30 | London
# Bob | 25 | Paris
# Carolyn | 28 | Berlin
The table pattern works for any number of rows because the width stays constant across the loop. For label-value pairs where the key length varies, ljust is equally helpful. Using zip to pair labels with their values keeps the code compact while the padding makes the output easy to read at a glance.
Example 4: Aligning variable-width data
labels = ["User:", "Email:", "Status:"]
values = ["john", "john@example.com", "active"]
labels.zip(values).each do |label, value|
puts "#{label.ljust(10)} #{value}"
end
# Output:
# User: john
# Email: john@example.com
# Status: active
The label-value alignment works well for configuration displays, status panels, and any output where the left column has varying lengths. Unlike a table, this pattern uses just two columns and is easier to read when the values are short.
Example 5: When width is less than string length
Notice that ljust never truncates. If the width is less than or equal to the string’s length, Ruby returns the original string unchanged. This guarantee makes the method safe in formatting loops where the width might vary.
puts "Ruby".ljust(2) # "Ruby" (no padding needed)
puts "Ruby".ljust(4) # "Ruby" (exact fit)
That behavior makes ljust predictable in formatting code that may receive different widths. The method never shortens the string, so the original content stays intact. When you are writing formatting code that handles user-supplied values, this guarantee means you can call ljust without first checking whether the string already fits.
Common Patterns
Building CLI output
A reusable helper function that wraps ljust keeps formatting consistent across an entire script. The example below defines a print_key_value method that pads keys to a uniform width.
def print_key_value(key, value, width = 30)
puts "#{key.ljust(width)}: #{value}"
end
print_key_value("Version", "3.2.0")
print_key_value("Author", "Yukihiro Matsumoto")
print_key_value("License", "BSD-2-Clause")
# Output:
# Version: 3.2.0
# Author: Yukihiro Matsumoto
# License: BSD-2-Clause
The same idea works for structured log output. By combining ljust with a timestamp, you can create log lines where the severity level and message always start at the same column. The ljust call on the severity level keeps labels like “INFO” and “WARN” at a fixed width, so the message column lines up regardless of which level is being logged.
Generating fixed-width columns for logs
def log_line(level, message, width = 50)
timestamp = Time.now.strftime("%H:%M:%S")
puts "[#{timestamp}] #{level.ljust(8)} #{message.ljust(width)}"
end
puts log_line("INFO", "Application started")
puts log_line("DEBUG", "Loading configuration file")
puts log_line("ERROR", "Connection timeout after 30s")
puts log_line("WARN", "Deprecated API called")
# Output:
# [18:33:00] INFO Application started
# [18:33:00] DEBUG Loading configuration file
# [18:33:00] ERROR Connection timeout after 30s
# [18:33:00] WARN Deprecated API called
Edge Cases
Empty strings and special characters
ljust handles a few edge cases predictably. An empty string pads out to the full width, Unicode characters count correctly as single characters, and tab characters are treated as a single padding unit. The examples below show how each of these cases behaves, including multibyte characters like Japanese kanji.
puts "".ljust(5) # " "
puts " ".ljust(5) # " " (single space becomes 5)
puts "\t".ljust(5) # tabs also pad correctly
puts "日本語".ljust(10) # "日本語 " (Unicode works)
When you pass an empty string as the padding argument, Ruby raises an error because there is nothing to repeat. This is the only padstr value that causes a runtime error, so it is worth guarding against if the padding string comes from user input.
Padding with empty string
puts "Ruby".ljust(10, "") # Raises ArgumentError: zero width padding
A negative width argument also raises an ArgumentError, since there is no meaningful way to pad a string to a negative size.
Negative width
puts "Ruby".ljust(-5) # Raises ArgumentError: negative string size
If you are using ljust in a loop, keep the width value in one place so the layout stays consistent. That makes it easier to adjust later, especially when the text changes or the output needs to fit a different terminal size.
See Also
- String#slice — Extract substrings by index or range
- String#center — Center a string by padding on both sides
- String#lstrip — Remove leading whitespace from a string