按排序顺序获取哈希的键值

时间:2013-03-19 05:05:33

标签: ruby-on-rails hash

这是我的代码

{"wow"=>["wow"], "you"=>["you", "you"], "are"=>["are"], "a"=>["a"], "good"=>["good"], "guy"=>["guy"], "but"=>["but"], "sometime"=>["sometime"], "take"=>["take"], "very"=>["very"], "wrong"=>["wrong"], "decision"=>["decision"]}

我想得到结果

{"you"=>2, "are"=>1, "a"=>1, "good"=>1, "guy"=>1, "but"=>1, "sometime"=>1, "take"=>1, "very"=>1, "wrong"=>1, "decision"=>1,"wow" =>1}

我该怎么做才能帮助我

1 个答案:

答案 0 :(得分:3)

尝试

old_hash = {"wow"=>["wow"], "you"=>["you", "you"], "are"=>["are"], "a"=>["a"], "good"=>["good"], "guy"=>["guy"], "but"=>["but"], "sometime"=>["sometime"], "take"=>["take"], "very"=>["very"], "wrong"=>["wrong"], "decision"=>["decision"]}

new_hash = Hash.new
old_hash.each {|k,v| new_hash.merge!(k=>v.size) }