2013-10-27 39 views
0

您的Ruby專業人員會笑,但我對此感到很難過。我搜索並搜索了許多不同的東西,但沒有看到任何正確的東西。我想我只是習慣於在js和php中處理數組。這是我想要做的;考慮這個僞代碼:我找不到在Ruby中創建簡單的多維數組或哈希的方法

i = 0 
foreach (items as item) { 
    myarray[i]['title'] = item['title'] 
    myarray[i]['desc'] = item['desc'] 
    i++ 
} 

權,這樣的話我可以通過myarray中或訪問「標題」和「說明」由指數(I)環。世界上最簡單的事情。我發現有幾種方法可以使它在Ruby中工作,但它們都非常混亂或混亂。我想知道做到這一點的正確方法,也是最乾淨的。

+0

看在http://紅寶石文檔。 org/core-2.0.0/Enumerable.html#method-i-each_with_index - 也許這就是你想要的 –

回答

0

除非你實際更新my_array(這意味着有可能是一個更好的辦法來做到這一點),你可能想映射來代替:

items = [ 
    {'title' => 't1', 'desc' => 'd1', 'other' => 'o1'}, 
    {'title' => 't2', 'desc' => 'd2', 'other' => 'o2'}, 
    {'title' => 't3', 'desc' => 'd3', 'other' => 'o3'}, 
] 

my_array = items.map do |item| 
    {'title' => item['title'], 'desc' => item['desc'] } 
end 

items # => [{"title"=>"t1", "desc"=>"d1", "other"=>"o1"}, {"title"=>"t2", "desc"=>"d2", "other"=>"o2"}, {"title"=>"t3", "desc"=>"d3", "other"=>"o3"}] 
my_array # => [{"title"=>"t1", "desc"=>"d1"}, {"title"=>"t2", "desc"=>"d2"}, {"title"=>"t3", "desc"=>"d3"}] 
+0

啊,太棒了。這個答案也很有幫助。 –

0

我不太清楚你爲什麼要這樣做,因爲它看上去好像是items已經是一個哈希陣列了,在我的代碼下面,myarrayitems完全一樣。

嘗試使用each_with_index代替foreach循環:

items.each_with_index do |item, index| 
    myarray[index] = item 
end 

如果你在每個項目額外的屬性,如id或東西,那麼你會希望你添加的項目之前卸下這些額外的屬性到myarray

+0

編輯:哦,我明白了,我認爲那會奏效。謝謝!編輯之前:謝天謝地,這很有道理。但是,有沒有辦法爲myarray [index] ['title']和myarray [index] ['desc']之類的每個索引添加一組鍵,還是我不理解Ruby如何工作?如果有辦法做到這一點,我該如何初始化數組?那個部分也令我難以理解,因爲myarray = Array.new似乎不夠。 –

+0

@KeithCollins其實,你可以發佈什麼'項目包含在你的問題?我發佈的代碼現在並沒有真正做任何事情,我在頂部添加了一個註釋。 – jvperrin

+0

對,我試圖創建一個乾淨的數組,有一些東西從項目,從別處的一些東西。就像你說的,我想我可以從物品中刪除我不想要的東西,但單獨刪除它們會是一件痛苦的事情。因此,我的偏好仍然會像myarray [index] ['title'] = item ['title'] etc etc –

0
titles = ["t1", "t2", "t3"] 
descs = ["d1", "d2", "d3"] 

h= Hash.new 

titles.each.with_index{ |v,i| h[i] = {title: "#{v}" } } 

puts h[0][:title] #=> t1 
puts h   #=> {0=>{:title=>"t1"}, 1=>{:title=>"t2"}...} 

descs.each.with_index{ |v,i| h[i] = h[i].merge({desc: "#{v}" }) } 

puts h[0][:desc] #=> d1 
puts h   #=> {0=>{:title=>"t1", :desc=>"d1"}, 1=>...