从Ruby中的哈希列表创建嵌套哈希 [英] Create Nested Hashes from a List of Hashes in Ruby

查看:181
本文介绍了从Ruby中的哈希列表创建嵌套哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组类别及其值存储为哈希列表:

I have a set of categories and their values stored as a list of hashes:

r = [{:A => :X}, {:A => :Y}, {:B => :X}, {:A => :X}, {:A => :Z}, {:A => :X},
     {:A => :X}, {:B => :Z}, {:C => :X}, {:C => :Y}, {:B => :X}, {:C => :Y},
     {:C => :Y}]

我想获取每个值的计数及其类别,作为哈希值,如下所示:

I'd like to get a count of each value coupled with its category as a hash like this:

{:A => {:X => 4, :Y => 1, :Z => 1},
 :B => {:X => 2, :Z => 1},
 :C => {:X => 1, :Y => 3}}

如何有效地做到这一点?

How can I do this efficiently?

这是我到目前为止的内容(返回不一致的值):

Here's what I have so far (it returns inconsistent values):

r.reduce(Hash.new(Hash.new(0))) do |memo, x|
  memo[x.keys.first][x.values.first] += 1
  memo
end

我应该首先计算特定{:cat => :val}的所有实例的计数,然后创建哈希吗?我是否应该给出其他基本案例来减少和更改正文以检查nil案例(并在nil时分配零)而不是总是加1?

Should I first compute the counts of all instances of specific {:cat => :val}s and then create the hash? Should I give a different base-case to reduce and change the body to check for nil cases (and assign zero when nil) instead of always adding 1?

我最终更改了代码,并使用以下方法来获得嵌套哈希的更简洁方法:

I ended up changing my code and using the below method to have a cleaner way of achieving a nested hash:

r.map do |x|
  [x.keys.first, x.values.last]
end.reduce({}) do |memo, x|
  memo[x.first] = Hash.new(0) if memo[x.first].nil?
  memo[x.first][x.last] += 1
  memo
end

推荐答案

您的代码的问题是: memo 没有保存该值. 在循环外使用一个变量来保存该值就可以了:

The problem of your code is: memo did not hold the value. Use a variable outside the loop to hold the value would be ok:

memo = Hash.new {|h,k| h[k] = Hash.new {|hh, kk| hh[kk] = 0 } }

r.each do |x|
  memo[x.keys.first][x.values.first] += 1
end

p memo

此外,像这样直接初始化嵌套在哈希中的哈希将无效:

And what's more, it won't work to init a hash nested inside a hash directly like this:

# NOT RIGHT
memo = Hash.new(Hash.new(0)) 
memo = Hash.new({})

以下是有关设置默认值问题的更多链接: http://www.themomorohoax.com/2008/12/31/why-setting-the-default-value-of-a-hash-to-be-a-hash-is-rong

Here is a link for more about the set default value issue: http://www.themomorohoax.com/2008/12/31/why-setting-the-default-value-of-a-hash-to-be-a-hash-is-wrong

这篇关于从Ruby中的哈希列表创建嵌套哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆