2012-09-16 65 views
0

數組一直是我用過的每種語言中的墮落,但我處於一種需要在Rails中創建多個項目的動態數組的情況(注意 - 這些都與模型無關)。在Ruby on Rails中創建一個包含多個值的簡單數組

簡而言之,數組中的每個元素都應該包含3個值 - 一個詞,一種語言,一種翻譯成英語。例如,這裏有我想要做什麼:

myArray = Array.new 

然後我想一些值推到陣列(注意 - 實際內容是從其他地方取 - 雖然不是一個模型 - 和意志需要通過一個循環以復加,而不是硬編碼的,因爲它是在這裏):

myArray[0] = [["bonjour"], ["French"], ["hello"]] 

myArray[1] = [["goddag"], ["Danish"], ["good day"]] 

myArray[2] = [["Stuhl"], ["German"], ["chair"]] 

我想創建一個循環列出每個項目在一行上,像這樣:

<ul> 
<li>bonjour is French for hello</li> 
<li>goddag is Danish for good day</li> 
<li>Stuhl is German for chair</li> 
</ul> 

但是,我很苦惱(a)找出如何將多個值推送到單個數組元素和(b)如何循環顯示結果。

不幸的是,我沒有得到任何進展。我似乎無法計算出如何將多個值推送到單個數組元素中(通常情況是[]括號會包含在輸出中,我顯然不想 - 因此這可能是符號錯誤)。

我應該使用散列嗎?

目前,我有三個獨立的數組,這是我一直在做的,但我並不特別喜歡 - 也就是說,一個數組保存原始單詞,一個數組保存語言,以及一個最終陣列來保存翻譯。雖然它可行,但我相信這是一個更好的方法 - 如果我能解決它!

謝謝!

回答

1

好吧,讓我們說你有,你想在一個CSV文件中的話:

# words.csv 
bonjour,French,hello 
goddag,Danish,good day 
stuhl,German,chair 

現在,在我們的計劃,我們可以做到以下幾點:

words = [] 
File.open('words.csv').each do |line| 
    # chomp removes the newline at the end of the line 
    # split(',') will split the line on commas and return an array of the values 
    # We then push the array of values onto our words array 
    words.push(line.chomp.split(',')) 
end 

在此之後代碼被執行,單詞數組有三個項目,每個項目是一個基於我們的文件的數組。

words[0] # => ["bonjour", "French", "hello"] 
words[1] # => ["goddag", "Danish", "good day"] 
words[2] # => ["stuhl", "German", "chair"] 

現在我們要顯示這些項目。

puts "<ul>" 
words.each do |word| 
    # word is an array, word[0], word[1] and word[2] are available 
    puts "<li>#{word[0]} is #{word[1]} for #{word[2]}</li>" 
end 
puts "</ul>" 

這給出了以下的輸出:

<ul> 
<li>bonjour is French for hello</li> 
<li>goddag is Danish for good day</li> 
<li>stuhl is German for chair</li> 
</ul> 

而且,你不問,但是你可以通過使用特定陣列的訪問部分如下:

words[0][1] # => "French" 

這是告訴紅寶石,你想看看數組中的第一個(Ruby數組是否爲零)元素。Ruby發現這個元素([「bonjour」,「French」,「hello」])並且看到它也是一個數組。然後,您詢問該數組的第二項([1]),Ruby返回字符串「French」。

+0

此外,語法words = []和words = Array.new是等同的。 –

+0

謝謝!這給了我一些線索。然而,不幸的是,內容來自不同的來源 - 沒有像CSV文件那麼整潔!但這是一個開始 - 歡呼! – Graeme

+0

CSV文件只是一個例子。如果你有一個單詞,語言,翻譯的數組,你可以用myArray.push(...)將它推入你的myArray。 –

0

你的意思是這樣的嗎?

myArray.map{|s|"<li>#{[s[0],'is',s[1],'for',s[2]].join(" ")}</li>"} 
0

感謝您的幫助!我設法根據您的建議找出解決方案

爲了解決這個問題的其他人的利益,這裏是我的遺漏代碼。注意:我使用了三個稱爲文本,語言和翻譯的變量,但我想你可以用三個單獨的元素替換這些變量,就像Jason上面所說的那樣。

在控制器(內容正在通過一個循環加):

#loop start 

my_array.push(["#{text}", "#{language}", "#{translation}"]) 

#loop end 

在查看:

<ul> 

<% my_array.each do |item| %> 

<li><%= item[0] # 0 is the original text %> is 
<%= item[1] # 1 is the language %> for 
<%= item[2] # 2 is the translation %></li> 

<% end %> 

</ul> 

再次感謝!

相關問題