Sometimes we want to place padding on the start or end of strings. The Ruby ljust
and rjust
methods left and right justify strings.
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.
rjust
exampleTo 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.
ljust
with an argument of 10, which gives us a 10-char
string
with spaces on the right.rjust
with an argument 10, which yields a 10-char
string
with spaces on the left (leading spaces).ljust
with a special character, so padding is added as exclamation mark characters.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]
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.
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***
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
.