如何在字符串末尾添加空格?
How do I add spaces to the end of my string?
我正在使用 Ruby 2.4。如何在字符串末尾添加任意数量的空格?我以为是 ljust 但是
2.4.0 :003 > line = "abcdef"
=> "abcdef"
2.4.0 :004 > line = line.ljust(4, " ")
=> "abcdef"
注意我的字符串没有改变。我做错了什么?
ljust()
的整数必须大于字符串的长度,否则将不追加任何内容。由于 line
是六个字符,我相信你想要:
line = "abcdef"
line = line.ljust(10, " ")
这将在字符串中已有的六个字符后添加四个空格。
您也可以按照以下方式做一些事情:
line = line.ljust(line.length + 4, " ")
您可以添加一个空格的倍数:
line = "abcdef"
line + ' '*5
#=> "abcdef "
line
#=> "abcdef"
或使用 concat
修改字符串。
line.concat(' '*5)
#=> "abcdef "
line
#=> "abcdef "
我正在使用 Ruby 2.4。如何在字符串末尾添加任意数量的空格?我以为是 ljust 但是
2.4.0 :003 > line = "abcdef"
=> "abcdef"
2.4.0 :004 > line = line.ljust(4, " ")
=> "abcdef"
注意我的字符串没有改变。我做错了什么?
ljust()
的整数必须大于字符串的长度,否则将不追加任何内容。由于 line
是六个字符,我相信你想要:
line = "abcdef"
line = line.ljust(10, " ")
这将在字符串中已有的六个字符后添加四个空格。
您也可以按照以下方式做一些事情:
line = line.ljust(line.length + 4, " ")
您可以添加一个空格的倍数:
line = "abcdef"
line + ' '*5
#=> "abcdef "
line
#=> "abcdef"
或使用 concat
修改字符串。
line.concat(' '*5)
#=> "abcdef "
line
#=> "abcdef "