为什么十进制值显示为“0”?

时间:2013-07-24 05:06:03

标签: ruby hash floating-point key-value

我正在使用此代码填充嵌套哈希结构中的值:

metrics_hash = Hash[ @metrics_array.map {|key| [key, nil] }]
demos_hash = Hash[@demos_types_array.map {|key| [key, metrics_hash] } ]

demos_hash.each do |demo , metric_hash |
    metric_hash.each do |metric , value |
        demo_index = @demos_types_array.index(demo)
        metric_index = @metrics_array.index(metric)
        offset = @demos_types_array.length() 
        value_index = metric_index * offset + demo_index 
        val = @demo_vals[value_index]
        metric_hash[metric] = val

    end
   puts "#{demo.inspect} => #{metric_hash.inspect} "
end
row_hash = row_hash.merge!({"demos" => demos_hash } )
end

(为了使上面的代码更具可读性,我删除了一些打印语句。)

当我打印row_hash时,val中的demos_hash值为十进制数,显示为"0"

demos"=>{"Ind.2+"=>{"AMA(000)"=>"0", "Shr% [Total TV Eng]"=>"0", "#Stations"=>"25"}, 
"A18+"=>{"AMA(000)"=>"0", "Shr% [Total TV Eng]"=>"0", "#Stations"=>"25"}, 
"A25-54"=> {"AMA(000)"=>"0", "Shr% [Total TV Eng]"=>"0", "#Stations"=>"25"}, 
"A18-49"=> {"AMA(000)"=>"0", "Shr% [Total TV Eng]"=>"0", "#Stations"=>"25"}, 
"A18-34"=> {"AMA(000)"=>"0", "Shr% [Total TV Eng]"=>"0", "#Stations"=>"25"}, 
"A55+"=> {"AMA(000)"=>"0", "Shr% [Total TV Eng]"=>"0", "#Stations"=>"25"}, 
"F25-54"=> {"AMA(000)"=>"0", "Shr% [Total TV Eng]"=>"0", "#Stations"=>"25"}, 
...........
"C2-11"=> {"AMA(000)"=>"0", "Shr% [Total TV Eng]"=>"0", "#Stations"=>"25"}}}

上面的大多数"0"值都是以某种方式转换为"0"的小数。请注意,站的值不受影响。上面的值是从这个数组中插入的:

 demo_values = ["5.1", "5.1", "3.3", "3", "2.5", "1.9", "0", "0", "0", "3.3", "3",      
 "2.5", "2.5", "0", "0", "0.6", "0.6", "0.7", "0.6", "1.1", "0.7", "0", "0", "0", "1.4", 
 "1.2", "2.2", "0.9", "0", "0", "25", "25", "25", "25", "25", "25", "25", "25", "25", 
 "25", "25", "25", "25", "25", "25"]

请注意此行的输出:

  puts "#{demo.inspect} => #{metric_hash.inspect} "

代码如下:

  "A18-34" => {"AMA(000)"=>"2.5", "Shr% [Total TV Eng]"=>"1.1", "#Stations"=>"25"} 

如您所见,数组中的大多数数字都是小数。

该程序正确填充metrics_hash。当我打印包含上面row_hash的整个demos_hash时会出现问题。可能会发生什么?

我检查了所有变量的类,并试图输出数字但没有运气,我似乎无法取得进展。

有人可以帮助我了解如何继续吗?

1 个答案:

答案 0 :(得分:4)

我认为你忽略了真正的问题:demos_hash中的每个值都是完全相同的对象。因此,如果您更改其中一个值,则实际上是在更改它们。当你这样做时:

demos_hash = Hash[@demos_types_array.map {|key| [key, metrics_hash] } ]

您没有制作metrics_hash的任何副本,只是为demos_hash的每个值分配相同的引用。我怀疑你只需要制作副本:

demos_hash = Hash[@demos_types_array.map {|key| [key, metrics_hash.dup] } ]
# ----------------------------------------------------------------^^^^

这将为您提供demos_hash值中不同的哈希值,事情应该开始变得更有意义。