2013-03-28 99 views
0

我有這樣的散列:提取關鍵值對從散列

{ 
    "results"=>[ 
    { 
     "name"=>"Pete Gallego", 
     "party"=>"D", 
     "state"=>"TX", 
     "district"=>"23", 
     "phone"=>"202-225-4511", 
     "office"=>"431 Cannon House Office Building", 
     "link"=>"http://gallego.house.gov" 
    }, 
    { 
     "name"=>"John Cornyn", 
     "party"=>"R", 
     "state"=>"TX", 
     "district"=>"Senior Seat", 
     "phone"=>"202-224-2934", 
     "office"=>"517 Hart Senate Office Building", 
     "link"=>"http://www.cornyn.senate.gov" 
    }, 
    { 
     "name"=>"Ted Cruz", 
     "party"=>"R", 
     "state"=>"TX", 
     "district"=>"Junior Seat", 
     "phone"=>"202-224-5922", 
     "office"=>"B40b Dirksen Senate Office Building", 
     "link"=>"http://www.cruz.senate.gov" 
    } 
    ] 
} 

我試圖在這樣的視圖,以顯示信息:

name Pete Gallego 
Party D 
state TX 
district 23 
. . . 
放置之前每個鍵

等它的價值。

當我嘗試這樣的事:

<ul> 
    <% @my_hash.values[0].each do |key, value| %> 
     <li><%= "#{key.to_s} #{value.to_s}" %> </li> 
    <% end %> 
</ul> 

我得到類似於一個觀點:

- {"name"=>"Pete Gallego", "party"=>"D", "state"=>"TX", "district"=>"23", "phone"=>"202-225-4511", "office"=>"431 Cannon House Office Building", "link"=>"http://gallego.house.gov"} 
- {"name"=>"John Cornyn", "party"=>"R", "state"=>"TX", "district"=>"Senior Seat", "phone"=>"202-224-2934", "office"=>"517 Hart Senate Office Building", "link"=>"http://www.cornyn.senate.gov"} 
- {"name"=>"Ted Cruz", "party"=>"R", "state"=>"TX", "district"=>"Junior Seat", "phone"=>"202-224-5922", "office"=>"B40b Dirksen Senate Office Building", "link"=>"http://www.cruz.senate.gov"} 

我不知道爲什麼,如果我打印的關鍵to_s其次價值to_s,我得到每個行項目的整個散列。我誤解了一些東西。

回答

4

您正在循環數組,但您還需要遍歷每個數組項(這是散列)中的每個鍵 - 值對。這可能會解決它:

<ul> 
    <% @my_hash.values[0].each do |item| %> 
     <% item.each do |key,value| %> 
      <li><%= "#{key.to_s} #{value.to_s}" %> </li> 
     <% end %> 
    <% end %> 
</ul> 
+0

你也可以'@my_hash ['results']'而不是'@ my_hash.values [0]''。 –