【问题标题】:How to sort a hash by value in descending order and output a hash in ruby?如何按值按降序对哈希进行排序并在 ruby​​ 中输出哈希?
【发布时间】:2012-10-24 08:14:37
【问题描述】:
output.sort_by {|k, v| v}.reverse

对于键

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

Hash[h.sort]

现在我有这两个。但我正在尝试按值按降序对哈希进行排序,以便它返回

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

提前致谢。

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

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

【问题讨论】:

  • 记住哈希在 Ruby 1.9 之前没有顺序

标签: ruby-on-rails ruby sorting hash


【解决方案1】:

试试:

Hash[h.sort.reverse]

这应该返回你想要的。

编辑:

按价值来做:

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

【讨论】:

  • 但是排序的关键思想,我正在尝试对值进行排序
  • hmmm....我也认为是这样。我怎么会看到 unless1sunday1or1on2of2due1the5is1day2saturday1rent1falls1first2month2a1.. 所有键和值都粘在 irb 中。
  • 它对我来说非常好。您使用的不是这个测试哈希吗?
  • 不...好吧,如果这是对其进行排序的方式。那么它可能会导致它输出错误的哈希值。我会仔细检查。还是谢谢。
  • “我怎么会看到除非1sunday1or1on2of2due1the5is1day2saturday1rent1falls1first2month2a1”,你用的是什么版本的Ruby?
【解决方案2】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-29
    • 2019-08-11
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 2011-03-10
    相关资源
    最近更新 更多