2015-02-17 95 views
1

我有內容表數據迭代:如何通過嵌套陣列

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] 

所有幫助表示讚賞。

回答

2

您的代碼幾乎是正確的。問題在於,您要連接多個puts調用,而您應該連接String參數,並使用單個puts調用。

array = [['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) + 
     i[1].to_s.ljust(col2Width) + 
     i[2].to_s.ljust(col3Width) 
end 
+0

謝謝,西蒙娜!這是令人尷尬的「顯而易見」。我正在學習編程,這是一個有趣的現象:有時我試圖解決某些問題越困難,越難看到「明顯」的現象。讓腦部更頻繁地休息可能是必不可少的...... – sqrcompass 2015-02-17 22:07:11

+0

由於列0和1已經是字符串,所以不需要在它們上調用'to_s'。 'puts'會減少到'i [0] .ljust(col1Width)+ i [1] .ljust(col2Width)+ i [2] .ljust(col3Width)' – 2015-02-18 02:36:35

+0

@DanielCukier'to_s'是第三個索引,否則你會嘗試在Fixnum上調用'ljust'。 – 2015-02-18 09:29:13

1

我已經根據來自請求dgilperez

我們有子陣列,在每個三個元素的數組加入的說明。 對於子數組中的每個項目,我們有三種不同的格式值。 將格式化值存儲在數組中也很方便。

lines = [lineWidth/4, lineWidth/2, lineWidth/4] 

現在,我們需要管理一個循環每個子陣列

array.each do |i| 
    i.map 
end 

...我們需要當前元素的索引來獲得相應的格式值。

array.each do |i| 
    i.map.with_index 
end 

現在我們實現其對於每一項的ž子陣列

i.map.with_index{|z, index| z.to_s.ljust(lines[index])} 

執行的塊...和指數處於範圍[0,1,2] 。 所以對於第一項,我們將使用第一格式化值等

索引== 0,線[指數] ==的lineWidth/4

索引== 1,線[指數] ==的lineWidth/2

該塊返回一個字符串數組,因爲我們通過函數map組織了一個循環。檢查地圖方法的文檔here

現在,我們需要所有的字符串連接成一個與方法加入

i.map.with_index{|z, index| z.to_s.ljust(lines[index])}.join 

,並返回最終的字符串 - 添加方法提出塊之前

puts i.map.with_index{|z, index| z.to_s.ljust(lines[index])}.join 

這裏是最終代碼

array = [['Chapter 1', 'Numbers', 1],['Chapter 2', 'Letters', 72],['Chapter 3', 'Variables', 118]] 

lineWidth = 80 
lines = [lineWidth/4, lineWidth/2, lineWidth/4] 

array.each do |i| 
    puts i.map.with_index{|z, index| z.to_s.ljust(lines[index])}.join 
end 
+1

你能解釋你的代碼嗎? – dgilperez 2015-02-19 00:06:16

+1

done @dgilperez – 2015-02-19 09:39:17