从散列中提取键值对

时间:2013-03-28 13:13:33

标签: ruby ruby-on-rails-3 hash erb

我有这个哈希:

{
  "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,我将获得每个订单项的整个哈希值。我误解了一些事情。

1 个答案:

答案 0 :(得分: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>