合并两个哈希并按键

时间:2017-01-23 03:29:42

标签: ruby-on-rails arrays hash grouping

我尝试将两个哈希合并到一个数组中,这样就可以在这样的表中显示它们:

enter image description here

现在我只能安排数组使用这种格式: [{" Motivation" => 4," Leadership" => 3," Innovation" => 1},{" Leadership&#34 ; => 2,"动机" => 3,"创新" => 1}]

在我的模型中,我有这段代码:

  def rates_table_index

  total = []

  ...
  ...
  slf_cc = ...

  self_cc = {}

  slf_cc.each do |cc|
    self_cc[cc.title] = cc.rate
  end

  total << self_cc

  other_cc = {}

  other_ccs = ...

  other_ccs.each do |cc|
    other_cc[cc.title] = cc.rate
  end

  total << other_cc

  result = total

end

标题和费率是用户的输入,因此我不知道如何通过键对值进行分组。

在我看来,我得到了这个:

<h2>Table</h2>
<table class="table">
  <thead>
  <tr>
    <th>Column 1</th>
    <th>Column 2</th>
    <th>Column 3</th>
  </tr>
  </thead>
  <tbody>

  <% @model.rates_table_index.each do |title, values| %>
          <tr>
            <td><%= title %></td>
            <td><%= values[0] %></td>
            <td><%= values[1] %></td>
          </tr>
      <% end %>
  </tbody>
</table>

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

创建一个带标题的哈希('Motivation','Leadership'等)作为键和数组([4,3][3,2]等)作为值。

# self_cc = {"Motivation"=>4, "Leadership"=>3, "Innovation"=>1}
# other_cc = {"Leadership"=>2, "Motivation"=>3, "Innovation"=>1}

rates = {}

keys = self_cc.keys
keys.each do |k|
  rates[k] = [self_cc[k], other_cc[k]]
end

# rates
# => {"Motivation"=>[4, 3], "Leadership"=>[3, 2], "Innovation"=>[1, 1]}

通过迭代视图中的哈希来显示数据。

<% rates.each do |title, values| %>
  <tr>
    <td><%= title %></td>
    <td><%= values[0] %></td>
    <td><%= values[1] %></td>
  </tr>
<% end %>

答案 1 :(得分:0)

已回答here

在问题的上下文中重述相同内容,如下所示:

[self_cc, other_cc].reduce({}) {|h,pairs| pairs.each {|k,v| (h[k] ||= []) << v}; h}