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"}

我不确定为什么,如果我打印 keyto_s后跟 value to_s,我会得到每个行项目的整个散列。我误解了一些东西。

4

1 回答 1

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>
于 2013-03-28T13:27:39.867 回答