Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

justify
ruby
string
communitycreator

How to right justify a string in Ruby

okwudili onyejiaku

Overview

We can right justify a string in Ruby by using the rjust() method. The rjust method requires a mandatory parameter, an integer, which gives the number of spaces to use to justify the string, and an optional pad string.

Syntax

str.rjust(length, padStr)

Parameters

str: This is the string we want to right justify.

length: This is the number of whitespace or spaces to use to right justify str. It is an integer value and is mandatory. If the length of str is greater than length, str will not be right justified.

padStr: This is an optional string that we want to use to pad string str.

Return value

The value returned is a new string that has str right justified, with the length length and the optional padding padStr.

Code example

# create strings
str1 = "welcome"
str2 = " to"
str3 = "edpresso"

# pad the strings
puts str1.rjust(10)
puts str2.rjust(7, "dear")
puts str3.rjust(2)
Right justify strings in Ruby

Explanation

  • Lines 2-4: We create some strings.
  • Lines 7-9: We pad the strings we created and print their results.

RELATED TAGS

justify
ruby
string
communitycreator
RELATED COURSES

View all Courses

Keep Exploring