Ruby Tuesday – String#rjust

Today’s Ruby Tuesday is on String#rjust.

String#rjust takes an integer, N, and returns a string of length N with the string that rjust was invoked on right aligned.

"Name".rjust 20
# => "                Name"
"Email".rjust 20
# => "               Email"
"Password".rjust 20
# => "            Password"

If the integer value passed to rjust is larger than the length of the string to right justify, the return value is a new string with the same content as the original. We can see this by comparing the object_id of the string rjust is called on with the object_id of the resulting string.

"foobar".rjust(4)
# => "foobar"
f = "foobar"
# => "foobar"
f.object_id
# => 70206438160440
f.rjust(2).object_id
# => 70206429587280
f.rjust(2).object_id
# => 70206438091960

String#rjust can also take a non-empty string as its second argument, and uses that string as the characters to pad the result with.

"Password".rjust(20, '_')
# => "____________Password"
"Password".rjust(20, '_-_')
# => "_-__-__-__-_Password"
"Password".rjust(20, ("a".."z").to_a.join)
# => "abcdefghijklPassword"
"Password".rjust(20, "")
# ArgumentError: zero width padding
# from (pry):16:in `rjust'

–Proctor