2011-08-08 43 views
0

您好我正在从数据库中获取数据来创建一些图。我回来〜6000 +条目都有一个Type, Data, Month与他们相关联。我希望将这些全部组合到一个数据结构中,以便我可以利用不具有重复键的哈希性质来组合数据。红宝石嵌套哈希创建

例如:我有输出如..

'Component', 4.1167, 'June' 
'Component', 3.2167, 'June' 
'Component', 4.8667, 'June' 
'Component', 3.3833, 'June' 

我想打一个嵌套哈希看起来像:

{'Component' => {'June' => '15.5834'}} #where all of the data gets added 

数据又回到了我的程序为3个平行阵列。

这样我就可以浏览所有的数据,积累它,并允许散列的性质删除我的标签的重复。

这有可能以任何方式吗?

感谢 猎人

回答

2

取决于你如何获取数据从数据库返回的,你会看一些类似的...

my_hash = {} 
a1, a2, a3 = get_database_result #whatever you call here 
a1.each_with_index do |component,i| 
    month = a3[i] 
    val = a2[i] 
    month_hash = my_hash[component] #get the month has for the component 
    if month_hash.nil? #if it doesn't exist, create it 
    month_hash = {} 
    my_hash[component] = month_hash 
    end 
    num_val = month_hash[month].nil? ? 0 : month_hash[month] #find the existing numeric value or create a zero 
    num_val += val #increment by database value 
    month_hash[month] = num_val #insert the value 
end 
my_hash #return my_hash 
+0

数据回来为三个平行排列,感谢我给这个更新的代码是基于3个阵列 –

+0

我这是'{'Component'=> {nil =>'value'}}'出于某种原因,本月不会出现 –

+0

我到底是什么了,当了一枪 –

2

如果各行项目它们本身就是带有列名称的哈希类对象,因为如果它们是ActiveRecord实例,那么下面的代码会将它们合并到所需的最终哈希中。这是一个独立的例子。

@result = {} 
def f x 
    @result.merge!({ x[:c] => { x[:m] => x[:v] }}) do |k, o, n| 
    o.merge!(n) do |k, o, n| 
     o + n 
    end 
    end 
end 

f :c => 'Component', :v => 4.1167, :m => 'June' 
f :c => 'Component', :v => 3.2167, :m => 'June' 
f :c => 'Component', :v => 4.8667, :m => 'June' 
f :c => 'Component', :v => 3.3833, :m => 'June' 

p @result 

更新:啊哈,并行阵列?好了,你可以只改变合并来电:

f :c => components[i], :v => values[i], :m => months[i] 
+0

感谢您的想法,但我的类不从ActiveRecord继承。我正在使用mysql命令行来生成XML文件。所以我只是解析这些,而不是做我所看到的本地ruby db调用 –

+0

,尽管它并不重要。 f(x)将采用一个散列表示一个任意组件名称的数据的单行,并按照您的概述合并它。 – DigitalRoss