Question

I have a Hash in another hash, basically this:

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

This hash generate this:

operation_system => {version, count}*

A example:

{"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}}

How can I sum the count? In case, 4 +2 +3 +2...

I tried this, but its not working:

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

Always return zero.

Ps: sorry my english :P

Was it helpful?

Solution

You need to access the hash using a key, not an index. This should work.

2.0.0-p451 :006 > sum = os_versions["Mac OS"].inject(0) { |sum, tuple| sum += tuple[1] }
 => 12
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top