所以我正在学习Chris Pine的在线教程,我坚持使用这个程序。我正在做的事情我觉得这是教程中教授的内容吗?
这是程序
toc = [[1, "Reflections"], [2, "Glasgow Roots"], [3, "Retirement U-turn"], [4, "A Fresh Start"], [5, "Beckham"]]
title = "The table of contents of Sir Alex Ferguson' Biography"
toc.each do |x, y|
lineWidth = 15
puts title.center lineWidth
puts x.ljust(lineWidth/2) + y.rjust(lineWidth/2)
end
错误
toc.rb:8:in `block in <main>': undefined method `ljust' for 1:Fixnum (NoMethodError)
from toc.rb:5:in `each'
from toc.rb:5:in `<main>'
请帮忙。
答案 0 :(得分:3)
或者,您可以使用String#%
或Kernel#sprintf
:
puts '%-*s%*s' % [lineWidth/2, x, lineWidth/2, y]
printf "%-*s%*s\n", lineWidth/2, x, lineWidth/2, y
答案 1 :(得分:2)
x
类型Fixnum
没有ljust
方法。您可以通过String
方法将其强制转换为to_s
来修复它。
x.to_s.ljust(lineWidth/2)