命令`left`,`right`和`justify`

时间:2016-02-05 20:39:29

标签: ruby

line_width = 40
str = 'test'
puts (str.ljust(line_width))
puts (str.rjust(line_width))
puts (str.center(line_width))
puts (str.ljust(line_width)) + (str.rjust(line_width))

输出

test                                    
                                    test
                  test                  
test                                                                        test

第四行:

puts (str.rjust(line_width))

和第六行

puts (str.rjust(line_width))

具有相同的值40。为什么它们印在不同的位置?

1 个答案:

答案 0 :(得分:3)

如果你指定“pad-string”,那就更明显了:

puts 'test'.ljust(40, '<')
puts 'test'.rjust(40, '>')
puts 'test'.center(40, '-')
puts 'test'.ljust(40, '<') + 'test'.rjust(40, '>')

输出:

test<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>test
------------------test------------------
test<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>test