如何在哈希哈希中求和值?

时间:2014-04-25 14:47:04

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我在另一个哈希中有一个哈希,基本上是这样的:

@hash_os_versions = Hash.new{ |h,k| h[k] = Hash.new{|h, k| h[k] = 0} }

此哈希生成此:

operation_system => {version, count}*

一个例子:

{"Linux"=>{"Fedora"=>4, "Debian"=>2, "OpenSUSE"=>3, "Red Hat"=>2, "Ubuntu"=>2}, "Mac OS"=>{"OS X 10.4 Tiger"=>3, "OS X 10.6 Snow Leopard"=>4, "OS X 10.5 Leopard"=>3, "OS X 10.7 Lion"=>2}, "Windows"=>{"Windows 2000"=>3, "Windows 7"=>2, "Windows 98"=>2, "Windows Vista"=>2, "Windows XP"=>2}}

如何计算总数? 如果是4 + 2 + 3 + 2 ......

我试过这个,但它不起作用:

<%= sum = os_versions[1].inject(0) { |sum, tuple| sum += tuple[1] } %>

始终返回零。

Ps:对不起我的英文:P

1 个答案:

答案 0 :(得分:1)

您需要使用密钥而不是索引来访问哈希。这应该有用。

2.0.0-p451 :006 > sum = os_versions["Mac OS"].inject(0) { |sum, tuple| sum += tuple[1] }
 => 12