2013-07-24 32 views
0

我使用這個代碼在嵌套結構的散列來填充值:(。爲了使上述代碼更易讀我刪除一些打印語句)爲什麼十進制值顯示爲「0」?

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,所述valdemos_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"值的上面有那名高官小數ehow轉換爲"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。當我打印包含上面的demos_hash的整個row_hash時,會發生問題。可能發生了什麼?

我檢查了所有變量的類,並試圖施放數字,但沒有運氣,我似乎無法取得進展。

有人可以幫助我理解如何繼續?

回答

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的價值觀和不同的東西應該散列開始做更有意義。

相關問題