[英]how to sort hash in descending order with out changing position of same value ruby
[英]How to sort a hash by value in descending order and output a hash in ruby?
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
嘗試:
Hash[h.sort.reverse]
這應該返回你想要的。
編輯:
按價值來做:
Hash[h.sort_by{|k, v| v}.reverse]
嘗試這個:
Hash[h.sort_by{ |_, v| -v }]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.