Ruby Nubie - 该计划有什么问题?

时间:2014-08-31 12:15:43

标签: ruby string

所以我正在学习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>'

请帮忙。

2 个答案:

答案 0 :(得分:3)

或者,您可以使用String#%Kernel#sprintf

puts '%-*s%*s' % [lineWidth/2, x, lineWidth/2, y]

Kernel#printf

printf "%-*s%*s\n", lineWidth/2, x, lineWidth/2, y

答案 1 :(得分:2)

x类型Fixnum没有ljust方法。您可以通过String方法将其强制转换为to_s来修复它。

x.to_s.ljust(lineWidth/2)