Ljust, pad strings. Sometimes we want to place padding on the start or end of strings. The Ruby ljust and rjust methods left and right justify strings.
Method notes. Another method, center(), allows us to center a string—it applies both left and right padding. These 3 methods can be used to render columns of text.
Ljust, rjust example. To begin we use the ljust and rjust methods. We specify (as the first argument) the total number of characters we want the ending string to have.
Part 1 Here we invoke ljust with an argument of 10, which gives us a 10-char string with spaces on the right.
Part 2 We call rjust with an argument 10, which yields a 10-char string with spaces on the left (leading spaces).
Part 3 We use ljust with a special character, so padding is added as exclamation mark characters.
Part 4 We use a star character with the rjust padding to demonstrate the special padding.
value = "bird"# Part 1: use ljust to left-justify text.
result1 = value.ljust(10)
puts "[" + result1 + "]"# Part 2: use rjust to right-justify text.
result2 = value.rjust(10)
puts "[" + result2 + "]"# Part 3: use ljust to left-justify text with special char.
result3 = value.ljust(10, "!")
puts "[" + result3 + "]"# Part 4: use rjust to right-justify text with special char.
result4 = value.rjust(10, "*")
puts "[" + result4 + "]"[bird ]
[ bird]
[bird!!!!!!]
[******bird]
Center. Sometimes a string must be centered in program output. This is helpful for preformatted text like HTML. The center method evenly pads the left and right sides.
Tip You can specify a padding character. The default character is a space, but we can use any character.
Warning If you call center() on a string that is too long to be centered in that size, the method will do nothing.
# This string has 8 chars.
value = "prytanes"# Center with spaces to size of 10.
a = value.center(10)
puts "[" + a + "]"# Center with stars to size of 13.
b = value.center(13, "*")
puts b[ prytanes ]
**prytanes***
A review. We invoked ljust, rjust and center with arguments to place padding around strings. The argument passed to these methods is the desired size of the resulting string.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 18, 2024 (edit).