String.* / center / ljust / rjust
Methods for padding a string to a specified width (aligning with fill characters) or repeating it.
Syntax
# Centers the string within the specified width. string.center(width) string.center(width, pad_char) # Left-aligns the string (pads on the right). string.ljust(width) string.ljust(width, pad_char) # Right-aligns the string (pads on the left). string.rjust(width) string.rjust(width, pad_char) # Repeats the string n times. string * n
Method List
| Method | Description |
|---|---|
| center(width, pad=' ') | Pads the string on both sides with the fill character to reach the specified width, centering the text. Uses a space as the default fill character. |
| ljust(width, pad=' ') | Pads the string on the right with the fill character to reach the specified width, left-aligning the text. |
| rjust(width, pad=' ') | Pads the string on the left with the fill character to reach the specified width, right-aligning the text. Use rjust(n, "0") to zero-pad numbers. |
| str * n | Returns a new string consisting of the original string repeated n times. |
Sample Code
text = "Ruby" # Center the string. puts text.center(10) # " Ruby " puts text.center(10, "*") # "***Ruby***" # Left-align (pad on the right). puts text.ljust(10) # "Ruby " puts text.ljust(10, "-") # "Ruby------" # Right-align (pad on the left). puts text.rjust(10) # " Ruby" puts text.rjust(10, "0") # "000000Ruby" # Zero-pad numbers (useful for dates, sequential numbers, etc.). puts "5".rjust(3, "0") # 005 puts "12".rjust(3, "0") # 012 puts "123".rjust(3, "0") # 123 (no change if already at or beyond the width) # Repeat a string with the * operator. puts "=-" * 10 # =-=-=-=-=-=-=-=-=-=- puts "Ruby " * 3 # Ruby Ruby Ruby # Useful for formatting table output. ["Item", "Price", "Qty"].each do |header| print header.ljust(10) end puts
Notes
center, ljust, and rjust are used for formatting text output. They are handy for aligning columns in command-line tools or decorating log headings. If the specified width is already less than or equal to the string's length, the string is returned unchanged.
You can use rjust(n, "0") to zero-pad numbers, but sprintf or string formatting (e.g., "%03d") works directly with numeric values, so it may be more appropriate when dealing with numbers specifically.
For string formatting, see sprintf() / % operator. To get the length of a string, use length / size.
If you find any errors or copyright issues, please contact us.