如何按值按降序对散列进行排序并在 ruby​​ 中输出散列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13216092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:58:54  来源:igfitidea点击:

How to sort a hash by value in descending order and output a hash in ruby?

ruby-on-railsrubysortinghash

提问by tipsywacky

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 }

Thanks in advance.

提前致谢。

Edit: 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

回答by Luke

Try:

尝试:

Hash[h.sort.reverse]

This should return what you want.

这应该返回你想要的。

Edit:

编辑:

To do it by value:

要按值执行此操作:

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

回答by Jeweller

Try this:

尝试这个:

Hash[h.sort_by{ |_, v| -v }]