Reputation: 119
Suppose I have the following hash table in ruby,
H = {"I"=>3, "Sam"=>2, "am"=>2, "do"=>1, "not"=>1, "eat"=> 1}
I want to construct the following hash table N from H
N = {"1" => 3, "2"=>2, "3"=>1}
where 3 in value signifies number of hash entires with value "1" in H (e.g. "do"=>1, "not"=>1, "eat"=> 1
, therefore "1" => 3
)
Is there any easy way in ruby to construct the N hash table from H??
Thanks in advance!!!
Upvotes: 0
Views: 944
Reputation: 7719
Alternate solution:
H.values.sort.inject(Hash.new(0)) {|ac,e| ac[e.to_s]+=1;ac}
# {"1"=>3, "2"=>2, "3"=>1}
Upvotes: 0
Reputation: 15515
Hash[H.values.group_by{|i| i}.map {|k,v| [k, v.count]}]
Update: to get strings as keys and sorted by key:
Hash[h.values.group_by{|i| i}.map {|k,v| [k.to_s, v.count]}.sort]
Upvotes: 4
Reputation: 3072
Try this,
N = {}
H.values.each { |t| N["#{t}"] = (N["#{t}"] || 0) + 1}
Upvotes: 0