Rails 3.2.1:为什么在控制器方法中迭代只读取最后一个键值对中的散列?

问题描述:

我试图遍历散列在我控制器方法Rails 3.2.1:为什么在控制器方法中迭代只读取最后一个键值对中的散列?

@trsesh_counts.each do |trsesh_mode, trsesh_count| 
    @hash = "#{trsesh_mode} (#{trsesh_count})" 
    end 

以我视图,我所说的实例变量@hash:

 <% @trsesh_counts.each do |trsesh_mode, trsesh_count| %> 
      <%= "#{trsesh_mode} (#{trsesh_count})" %> 
      <% end %> 
     vs. <%= @hash %> where array = <%= @trsesh_counts %> 

,其输出如下:

(7) Running (12) Weightlifting (1) vs. Weightlifting (1) where array = {""=>7, "Running"=>12, "Weightlifting"=>1} 

为什么是@hash实例变量fetc只搜索散列的最后一个键值对(举重(1))?我如何获得@hash来输出整个散列,就像我在视图中迭代一样?

编辑:由于某种原因,我可以调用每个键值对的提取,但我仍然无法迭代每对。

h = @trsesh_counts 
     @hash = h.fetch("Running") 

...返回12,“运行”键的值。

您的代码不起作用,因为您每次通过@trsesh_counts循环时都重新指定@hash的值。此外,为了清楚起见,我保留了变量名称,但我建议更改@hash的名称,因为它实际上是一个字符串,而不是散列。的@hash = ""初始分配

@hash = "" 
@trsesh_counts.each do |trsesh_mode, trsesh_count| 
    @hash << "#{trsesh_mode} (#{trsesh_count}) " 
end 

注为空字符串,那么每块内使用<<:改变你原来的代码段将。 (我还在字符串值中包含了尾部空格)。这将构建@hash的值,而不是在每次迭代中为其重新分配新值。

这也可以使用被缩短Enumerable#each_with_object像这样:

@hash = @trsesh_counts.each_with_object("") { |ary, str| str << "#{ary[0]} (#{ary[1]}) " }