-3

有三个哈希值。每个散列都会产生一个键/值对。

当合并并输出到一个 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

4

3 回答 3

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
于 2013-03-23T20:26:33.663 回答
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) }
于 2013-03-23T20:29:14.120 回答
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}"
于 2013-03-23T20:37:06.627 回答