Positioning strings

suggest change

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

To left-justify string, use the ljust method. This takes in two parameters, an integer representing the number of characters of the new string and a string, representing the pattern to be filled.

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 the rjust method. This takes in two parameters, an integer representing the number of characters of the new string and a string, representing the pattern to be filled.

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 the center method. This takes in two parameters, an integer representing the width of the new string and a string, which the original string will be padded with. The string will be aligned to the center.

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