如何在Ruby中的字符串开始时添加一定数量的空间



我正在使用Ruby 2.3。如何在字符串的开头添加一定数量的空间?我认为rjust是这样做的,但是当我想在字符串的前部添加1个空间时,这些呼叫什么都不做。

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"

尝试

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"

如果要将其格式化为特定宽度:

line =  "  29  25  13 M10-19 14    23:36  7:36    826 HYLLBERG MARCO      WI Kenosha"
'%76s' % line

sprintf格式指令使以这种方式组织事物变得容易。

最新更新