Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 合并哈希时包括空k/v对_Ruby_Hashtable - Fatal编程技术网

Ruby 合并哈希时包括空k/v对

Ruby 合并哈希时包括空k/v对,ruby,hashtable,Ruby,Hashtable,有三个散列。每个散列产生一个键/值对 合并并输出到json文件时,唯一可见的k/v对是包含数据的k/v对 例如: employee_hours[ name ] = {"Hours" => hours} employee_revenue [ name ] = {"Revenue" => revenue} employee_activations [ name ] = {"Activations" => activations} require 'js

有三个散列。每个散列产生一个键/值对

合并并输出到json文件时,唯一可见的k/v对是包含数据的k/v对

例如:

employee_hours[ name ] =         {"Hours" => hours}
employee_revenue [ name ] =      {"Revenue" => revenue}
employee_activations [ name ] =  {"Activations" => activations}
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}"
如果任何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}
编辑


我的当前代码列在这里:

您需要为默认值定义一个哈希并合并到其中。假设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

听起来好像您需要定义一个“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) }
使用哈希默认值 您可以使用参数为哈希设置默认值。例如:

employee_hours[ name ] =         {"Hours" => hours}
employee_revenue [ name ] =      {"Revenue" => revenue}
employee_activations [ name ] =  {"Activations" => activations}
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}"

您是否尝试过直接将零值分配给它们?据我所知,Ruby哈希的k/v对只有在被直接引用至少一次的情况下才会被输出。只是尝试了一下……仍然不起作用。前两个散列与第三个employee_激活合并,第三个散列似乎覆盖了其他两个散列的值。您预期的结果是什么?你到底在哪里进行合并?请参阅问题中的要点。我不认为你的设置将为我所拥有的工作。