2014-08-31 95 views
2

所以我正在從Chris Pine的在線教程中學習,並且我堅持使用這個程序。我在做什麼,我覺得只是教程中教導的內容?Ruby Nubie - 程序出了什麼問題?

這是程序

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

你注意到代碼劃分爲奇數(15)由2,這意味着你的字段將是7個字符寬,你的線將是14個字符,而不是你可能預期的15個字符? – dcorking 2014-08-31 13:39:04

回答

2

您的xFixnum類型,它沒有ljust方法。您可以通過to_s方法將其轉換爲String來修復它。

x.to_s.ljust(lineWidth/2) 
+1

謝謝。解決了它。瞭解它。 – 2014-08-31 12:51:07

+1

如果您的問題已解決,請接受答案,以便它不會顯示在「未答覆」列表中。 – dcorking 2014-08-31 13:15:09

+0

@dcorking,考慮到快速選擇可能會阻礙其他可能有趣的答案,有什麼問題。 – 2014-08-31 15:18:09

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 
+0

我喜歡這個,但提問者應該注意,爲了使這個答案的行爲與問題中的ljust/rjust代碼相同,他應該從格式中省略空格字符串,就像這個''% - * s%* s'' – dcorking 2014-08-31 13:35:42

+0

@dcorking,謝謝你指出。我相應地更新了答案。 – falsetru 2014-08-31 13:36:37