Ruby合并哈希值

时间:2017-05-23 08:06:10

标签: ruby-on-rails ruby hash

我编写了一个API来整理我的每日用户数据。

原始格式就像

"dau": {
      "2017-05-02": 1,
      "2017-05-04": 2,
      "2017-05-05": 2,
      }

"new_user": {
      "2017-05-02": 1,
      "2017-05-04": 0,
      "2017-05-07": 0,
}

很难在HTML表格中逐行显示。

因此,我希望格式成为这个格式。

但是,我不知道如何处理。

info: {
      "2017-05-02": {
            dau: 1,
            new_user: 1
      },
      "2017-05-04": {
            dau: 2,
            new_user: 0
      },
      "2017-05-05": {
            dau: 2
      },
      "2017-05-07": {
            new_user: 0
      }
}

3 个答案:

答案 0 :(得分:1)

假设你有data,那么

(data['dau'].keys + data['new_user'].keys).uniq.map { |k| [k, { dau: data['dau'][k].to_i, new_user: data['new_user'][k].to_i } ] }.to_h

如果您不想要默认/ 0值,那么

(data['dau'].keys + data['new_user'].keys).uniq.map { |k| [k, { dau: data['dau'][k], new_user: data['new_user'][k] }.compact ] }.to_h

输出:

{
    "2017-05-02" => {
            :dau => 1,
        :new_user => 1
    },
    "2017-05-04" => {
            :dau => 2,
        :new_user => 0
    },
    "2017-05-05" => {
        :dau => 2
    },
    "2017-05-07" => {
        :new_user => 0
    }
}

希望有所帮助......

答案 1 :(得分:1)

keys = (dau.keys + new_user.keys).uniq 
# [:"2017-05-02", :"2017-05-04", :"2017-05-05", :"2017-05-07"]

keys.each_with_object({}) do |key, result| 
  result[key] = {dau: dau[key], new_user: new_user[key] }.compact
end
# {:"2017-05-02"=>{:dau=>1, :new_user=>1},
# :"2017-05-04"=>{:dau=>2, :new_user=>0},
# :"2017-05-05"=>{:dau=>2},
# :"2017-05-07"=>{:new_user=>0}}

答案 2 :(得分:0)

这是each_with_object的另一种选择。它应该适用于任意数量的键:

data = {"dau": {
  "2017-05-02": 1,
  "2017-05-04": 2,
  "2017-05-05": 2
  },
"new_user": {
  "2017-05-02": 1,
  "2017-05-04": 0,
  "2017-05-07": 0
  }
}


info = Hash.new { |h, k| h[k] = {} }
info = data.each_with_object(info) do |(key, sub_h), h|
  sub_h.each do |date, i|
    h[date][key] = i
  end
end

p info
# {:"2017-05-02"=>{:dau=>1, :new_user=>1}, :"2017-05-04"=>{:dau=>2, :new_user=>0}, :"2017-05-05"=>{:dau=>2}, :"2017-05-07"=>{:new_user=>0}}