我有一个哈希:
[{:count=>274, :label=>"Minas Gerais"}, {:count=>300, :label=>"São Paulo"}, {:count=>73, :label=>"Rio de Janeiro"}, {:count=>11, :label=>"Espírito Santo"}, {:count=>41, :label=>"Paraná"}, {:count=>70, :label=>"Santa Catarina"}, {:count=>81, :label=>"Rio Grande do Sul"}, {:count=>23, :label=>"Bahia"}, {:count=>3, :label=>"Alagoas"}, {:count=>8, :label=>"Amazonas"}, {:count=>1, :label=>"Amapá"}, {:count=>24, :label=>"Ceará"}, {:count=>62, :label=>"Distrito Federal"}, {:count=>35, :label=>"Goiás"}, {:count=>2, :label=>"Maranhão"}, {:count=>7, :label=>"Mato Grosso do Sul"}, {:count=>6, :label=>"Mato Grosso"}, {:count=>11, :label=>"Pará"}, {:count=>11, :label=>"Paraíba"}, {:count=>29, :label=>"Pernambuco"}, {:count=>1, :label=>"Piauí"}, {:count=>6, :label=>"Rio Grande do Norte"}, {:count=>1, :label=>"Roraima"}, {:count=>4, :label=>"Sergipe"}, {:count=>2, :label=>"Tocantins"}]
我需要访问这些值并进行一些计算。 我正在使用迭代来在哈希中访问每个数组,如下所示:
<% region.each do |key| %>
<%= key %>
<br>
<% end %>
结果:
....
{:count=>11, :label=>"Espírito Santo"}
{:count=>41, :label=>"Paraná"}
{:count=>70, :label=>"Santa Catarina"}
....
在这个内部,我想得到每个计数和每个标签,所以我尝试了这个:
<% region.each do |key| %>
<%= key[0] %>
<%= key[1] %>
<br>
<% end %>
不工作,没有出现,我搜索但我找不到任何这样的例子。
答案 0 :(得分:3)
应该是
<% region.each do |item| %>
<%= item[:count] %>
<%= item[:label] %>
<br>
<% end %>
它实际上不是key
,它是数组的对象或项目。
答案 1 :(得分:1)
这样做
region = [{:count=>274, :label=>"Minas Gerais"}, {:count=>300, :label=>"São Paulo"}, {:count=>73, :label=>"Rio de Janeiro"}, {:count=>11, :label=>"Espírito Santo"}, {:count=>41, :label=>"Paraná"}, {:count=>70, :label=>"Santa Catarina"}, {:count=>81, :label=>"Rio Grande do Sul"}, {:count=>23, :label=>"Bahia"}, {:count=>3, :label=>"Alagoas"}, {:count=>8, :label=>"Amazonas"}, {:count=>1, :label=>"Amapá"}, {:count=>24, :label=>"Ceará"}, {:count=>62, :label=>"Distrito Federal"}, {:count=>35, :label=>"Goiás"}, {:count=>2, :label=>"Maranhão"}, {:count=>7, :label=>"Mato Grosso do Sul"}, {:count=>6, :label=>"Mato Grosso"}, {:count=>11, :label=>"Pará"}, {:count=>11, :label=>"Paraíba"}, {:count=>29, :label=>"Pernambuco"}, {:count=>1, :label=>"Piauí"}, {:count=>6, :label=>"Rio Grande do Norte"}, {:count=>1, :label=>"Roraima"}, {:count=>4, :label=>"Sergipe"}, {:count=>2, :label=>"Tocantins"}]
<% region.each do |hash| %>
<%= hash[:count] %><br>
<%= hash[:label] %>
<% end %>