有三个哈希。每个哈希都会产生一个键/值对。
当合并并输出到json文件时,唯一可见的k / v对是带数据的那些。
例如:
employee_hours[ name ] = {"Hours" => hours}
employee_revenue [ name ] = {"Revenue" => revenue}
employee_activations [ name ] = {"Activations" => activations}
如果任何k / v对不存在,我需要将它们包含在输出中,其值为0.00
。
我试图简单地在每个哈希表中包含来自其他哈希值的空k / v对,但是当合并时,它们会覆盖现有值。
employee_hours[ name ] = {"Hours" => hours, "Revenue" = "", Activations = ""}
employee_revenue [ name ] = {"Hours" => "", "Revenue" => revenue, Activations = ""}
employee_activations [ name ] = {"Hours" => "", "Revenue" => "", "Activations" => activations}
修改
我目前的代码列在此处:https://gist.github.com/hnanon/766a0d6b2b0f9d9d03fd
答案 0 :(得分:1)
您需要为默认值定义哈希并合并到其中。假设employee_final是您合并所有员工信息的哈希,
employee_defaults = { "Hours" => 0.0, "Revenue" => 0.0 }
employee_final.each_key do |name|
employee_final[name] = employee_defaults.merge(employee_final[name])
end
答案 1 :(得分:0)
听起来好像你需要定义一个'REQUIRED_KEYS'数组,并在哈希中添加检查它们的存在。这是实现这一目标的一种方法:
REQUIRED_KEYS = [ "A", "B", "C" ]
DEFAULT_VALUE = 0.0
REQUIRED_KEYS.each { |key| your_hash[key] = DEFAULT_VALUE if not your_hash.has_key?(key) }
答案 2 :(得分:0)
您可以使用Hash#new的参数来设置哈希的默认值。例如:
require 'json'
employee_hours = Hash.new(0.0)
employee_revenue = Hash.new(0.0)
employee_activations = Hash.new(0.0)
name = 'Bob'
{
'Hours' => employee_hours[name],
'Revenue' => employee_revenue[name],
'Activations' => employee_activations[name],
}.to_json
# => "{\"Hours\":0.0,\"Revenue\":0.0,\"Activations\":0.0}"