我有內容表數據迭代:如何通過嵌套陣列
array = [
['Chapter 1', 'Numbers', 1],
['Chapter 2', 'Letters', 72],
['Chapter 3', 'Variables', 118]
]
我試圖作爲像這樣的表來顯示陣列的內容:
Chapter 1 Numbers 1
Chapter 2 Letters 72
Chapter 3 Variables 118
這裏是我的代碼:
lineWidth = 80
col1Width = lineWidth/4
col2Width = lineWidth/2
col3Width = lineWidth/4
array.each do |i|
puts i[0].to_s.ljust(col1Width) + puts i[1].to_s.ljust(col2Width) + puts i[2].to_s.ljust(col3Width)
end
的問題是我不斷收到此錯誤:
chapter7-arrays.rb:48: syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '('
puts i[0] + puts i[1] + puts i[2]
^
chapter7-arrays.rb:48: syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '('
puts i[0] + puts i[1] + puts i[2]
所有幫助表示讚賞。
謝謝,西蒙娜!這是令人尷尬的「顯而易見」。我正在學習編程,這是一個有趣的現象:有時我試圖解決某些問題越困難,越難看到「明顯」的現象。讓腦部更頻繁地休息可能是必不可少的...... – sqrcompass 2015-02-17 22:07:11
由於列0和1已經是字符串,所以不需要在它們上調用'to_s'。 'puts'會減少到'i [0] .ljust(col1Width)+ i [1] .ljust(col2Width)+ i [2] .ljust(col3Width)' – 2015-02-18 02:36:35
@DanielCukier'to_s'是第三個索引,否則你會嘗試在Fixnum上調用'ljust'。 – 2015-02-18 09:29:13