2015-04-07 109 views
2

输入: -如何从阵列获取的散列值

array = [{"name"=>"id", "value"=>"123"}, 
     {"name"=>"type", "value"=>"app"}, 
     {"name"=>"codes", "value"=>"12"}, 
     {"name"=>"codes", "value"=>"345"}, 
     {"name"=>"type", "value"=>"app1"}] 

sample_hash = {} 

功能: -

array.map {|f| sample_hash[f["name"]] = sample_hash[f["value"]] } 

结果: -

sample_hash

=> {"id"=>"123", "type"=>"app", "codes"=>"345"} 

但我需要预期的结果应如下所示: -

sample_hash

=> {"id"=>"123", "type"=>["app","app1"], "codes"=>["12", "345"]} 

怎样才能让我的预期的输出?

+1

虽然这不是你问什么了,它会让你凑更容易,更好用,如果你有工作一个数组,即使是只有一个值的键例如''id“=> [”123“]' - 通过这种方式从哈希中获取值时,您不必检查是否返回了字符串或数组。 – mikej

+1

@mikej同意你的意见。 API一致性很有帮助。 –

回答

1

您可以使用new {|hash, key| block }哈希构造函数初始化sample_hash,以使默认情况下将此哈希中的值初始化为空数组。 这使得在第二阶段,其中,在初始数据组中的每个值被附加到下相应的“名称”索引值的阵列更容易:

sample_hash = Hash.new { |h, k| h[k] = [] } 
array.each { |f| sample_hash[f['name']] << f['value'] } 

Try it online

1

@ w0lf是正确的。相同但构造不同。

array.each_with_object({}) do |input_hash, result_hash| 
    (result_hash[input_hash['name']] ||= []) << input_hash['value'] 
end 
0

看到这个:

array.inject({}) do |ret, a| 
    ret[a['name']] = ret[a['name']] ? [ret[a['name']], a['value']] : a['value'] 
    ret 
end 

O/P:{"id"=>"123", "type"=>["app", "app1"], "codes"=>["12", "345"]}