Converting one hash to another hash in ruby -


convert following hash hash.

{["2013-08-15", "123", "user1"]=>1, ["2013-08-15", "456", "user1"]=>1, ["2013-08-09", "789", "user1"]=>5}  

convert above hash to

{["2013-08-15", "user1"]=>2, ["2013-08-09", "user1"]=>1}  

as can see first , second key, value pairs in hash have same date, different account, , same user, in case need count total number of user posts 2 {["2013-08-15", "user1"]=>2}

in last key, value pair, count should 1 because user posted 1 account ("789") though there 5 posts {["2013-08-09", "user1"]=>1}.

h = {["2013-08-15", "123", "user1"]=>1, ["2013-08-15", "456", "user1"]=>1, ["2013-08-09", "789","user1"]=>5}  hash[h.group_by{|k,v| k[0]}.map{|_,v| [v.flatten.values_at(0,2),v.size]}] # => {["2013-08-15", "user1"]=>2, ["2013-08-09", "user1"]=>1} 

or,

h = {["2013-08-15", "123", "user1"]=>1, ["2013-08-15", "456", "user1"]=>1, ["2013-08-09", "789","user1"]=>5}  h.each_with_object(hash.new(0)){|((d,_,u),_),hsh| hsh[[d,u]] +=1 } # => {["2013-08-15", "user1"]=>2, ["2013-08-09", "user1"]=>1} 

Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -