Positioning strings

suggest change

In Ruby, strings can be left-justified, right-justified, or centered.

To left-justify a string, use ljust. It takes the width of the new string and an optional pad string.

If the integer is greater than the length of the original string, the new string will be left-justified with the optional string parameter taking the remaining space. If the string parameter is not given, the string will be padded with spaces.

str = "abcd"
str.ljust(4)          => "abcd"
str.ljust(10)         => "abcd      "

To right-justify a string, use rjust. It takes the same width and optional pad string.

If the integer is greater than the length of the original string, the new string will be right-justified with the optional string parameter taking the remaining space. If the string parameter is not given, the string will be padded with spaces.

str = "abcd"
str.rjust(4)          => "abcd"
str.rjust(10)         => "      abcd"

To center a string, use center. It takes the width and an optional pad string. The original string is placed in the middle.

str = "abcd"
str.center(4)          => "abcd"
str.center(10)         => "   abcd   "

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents