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.
Detail 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 ]
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 ]
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.