Reputation: 5802
I have this hash:
{
"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"
}
]
}
I am attempting to display the information in a view like this:
name Pete Gallego
Party D
state TX
district 23
. . .
and so on with each key placed before its value.
When I attempt something like this:
<ul>
<% @my_hash.values[0].each do |key, value| %>
<li><%= "#{key.to_s} #{value.to_s}" %> </li>
<% end %>
</ul>
I get a view that resembles:
- {"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"}
I'm not sure why, if I'm printing the key to_s
followed by the value to_s
, that I'm getting the entire hash for each line item. I'm misunderstanding something.
Upvotes: 0
Views: 840
Reputation: 6652
You are looping the array but you also need to loop through each key-value pair in each array item (which is a hash). This will probably solve it:
<ul>
<% @my_hash.values[0].each do |item| %>
<% item.each do |key,value| %>
<li><%= "#{key.to_s} #{value.to_s}" %> </li>
<% end %>
<% end %>
</ul>
Upvotes: 4