如何按降序对值进行排序并在ruby中输出散列值? [英] How to sort a hash by value in descending order and output a hash in ruby?

查看:94
本文介绍了如何按降序对值进行排序并在ruby中输出散列值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

output.sort_by {|k, v| v}.reverse

和键

and for keys

h = {"a"=>1, "c"=>3, "b"=>2, "d"=>4}
=> {"a"=>1, "c"=>3, "b"=>2, "d"=>4}

Hash[h.sort]

现在我有这两个。但我试图按值降序排列哈希,以便它返回

Right now I have these two. But I'm trying to sort hash in descending order by value so that it will return

=> {"d"=>4, "c"=>3, "b"=>2, "a"=>1 }

在此先感谢。

编辑:
让我发布整个代码。

let me post the whole code.

def count_words(str)
  output = Hash.new(0)
  sentence = str.gsub(/,/, "").gsub(/'/,"").gsub(/-/, "").downcase
  words = sentence.split()
  words.each do |item|
    output[item] += 1 
  end
  puts Hash[output.sort_by{ |_, v| -v }]
  return Hash[output.sort_by{|k, v| v}.reverse]
end


推荐答案



Try:

Hash[h.sort.reverse]

这应该返回你想要的。

This should return what you want.

编辑:

b
$ b

To do it by value:

Hash[h.sort_by{|k, v| v}.reverse]

这篇关于如何按降序对值进行排序并在ruby中输出散列值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆