Natalia Natalia - 3 days ago 8
Ruby Question

How do I add a certain number of spaces to the beginning of a string in Ruby?

I'm using Ruby 2.3. How do I add a certain number of spaces to the beginning of a string? I thought rjust was the way to do it, but these calls do nothing when I want to add 1 space of padding to the front of the string ..

line = " 29 25 13 M10-19 14 23:36 7:36 826 HYLLBERG MARCO WI Kenosha"
# => " 29 25 13 M10-19 14 23:36 7:36 826 HYLLBERG MARCO WI Kenosha"
line.rjust(1)
# => " 29 25 13 M10-19 14 23:36 7:36 826 HYLLBERG MARCO WI Kenosha"

Answer

try

line = "  29  25  13 M10-19 14    23:36  7:36    826 HYLLBERG MARCO      WI Kenosha"
#=> "  29  25  13 M10-19 14    23:36  7:36    826 HYLLBERG MARCO      WI Kenosha"
line.prepend(" ")
#=> "   29  25  13 M10-19 14    23:36  7:36    826 HYLLBERG MARCO      WI Kenosha"
line.prepend(" " * 2) # for a variable number of spaces
#=> "    29  25  13 M10-19 14    23:36  7:36    826 HYLLBERG MARCO      WI Kenosha"
Comments