left pad with space in ruby

To left pad a string with spaces in Ruby, you can use the String#rjust method. This method takes the desired length of the resulting string as its first argument and the character you want to use for padding as its second argument (in this case, a space).

Here's an example of how to use rjust to left pad a string with spaces:

main.rb
str = "hello"
padded_str = str.rjust(10) # "     hello"
56 chars
3 lines

In this example, str is the original string we want to pad, and padded_str is the resulting string after we've added spaces to the left. The 10 argument specifies the total length we want padded_str to be, including the original str.

related categories

gistlibby LogSnag