Descending sort by value of a Hash in Ruby
You can have it cleaner, clearer and faster, all at once! Like this:
h.sort_by {|k,v| v}.reverse
I benchmarked timings on 3000 iterations of sorting a 1000-element hash with random values, and got these times:
h.sort {|x,y| -(x[1]<=>y[1])} -- 16.7s
h.sort {|x,y| y[1] <=> x[1]} -- 12.3s
h.sort_by {|k,v| -v} -- 5.9s
h.sort_by {|k,v| v}.reverse -- 3.7
Sort a hash by value in descending order and then key in ascending order ruby
In a comparison, arrays get evaluated first by their first elements, then by their second, etc. You can use this fact to enumerate sequential comparisons. Comparing by [-v, k]
first sorts by value (in reverse order) then by key.
>> trial_hash.sort_by{|k, v| [-v, k]}
=> [["key1", 1000], ["key3", 500], ["key4", 500], ["key5", 500], ["key6", 500], ["key2", 34]]
How to sort a hash by value in descending order and output a hash in ruby?
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]
Sort array of hash by key in descending order in Ruby
You can do
h.sort_by! { |k| -k[:bookings_nd] }
or
h.sort_by! { |k| k[:bookings_nd] }.reverse!
Also i guess this question is duplicate for Sorting an array in descending order in Ruby
Sort hash by length of values (descending)
You cannot sort a hash - that might be causing your confusion. There is no "internal" ordering of elements of a hash as it appears in an array.
You can, however, iterate over a hash in a certain order, e.g.
hash.sort_by {|k,v| v.length}.reverse.each do |k, v|
puts "k = #{k}, v = #{v}"
end
Sort array of hashes by value of hash property in descending order preserving the initial order of hash
results = [
{ "rating"=>6, "id"=>10699 },
{ "rating"=>3, "id"=>19985 },
{ "rating"=>6, "id"=>1029 }
]
results.sort_by.with_index { |h,i| [-h["rating"], i] }
#=> [{"rating"=>6, "id"=>10699},
# {"rating"=>6, "id"=>1029}
# {"rating"=>3, "id"=>19985}]
See the third paragraph of the doc Array#<=> for an explanation of how Ruby orders arrays. When Ruby orders results[0]
and results[2]
she compares [-6, 0]
with [-6, 2]
. Because the first elements of these arrays are equal (-6
), Ruby compares 0
with 2
to break the tie, so results[0]
is ordered before results[2]
.
Note that when the method Enumerable#sort_by has no block, it returns an enumerator. Here that enumerator is chained to Enumerator#with_index to produce another enumerator.
Ruby - sorting hashes into descending order by value
You are kinda mixing the sort and filtering out phases. My solution
- Filter results with
value >= 60
- Sort for values (descending,
-v
) Extract the first element for every array (the language name)
def my_languages(results)
results.select { |k, v| v >= 60 }.sort_by { |(k,v)| -v }.map(&:first)
end
Sorting Hash by value
Enumerable#sort_by
never promised to sort the enumerable inplace. It returns the result:
puts mapa.sort_by {|a,b| -b}
#⇒ sorted
or, in more idiomatic manner:
mapa.sort_by(&:last).reverse.each do |k, v|
puts ...
end
Please note, that when examining the output in irb
, the order might not correspond to the real order of elements in a hash, since irb
(with print formatters installed) has it’s own ideas on how to output hashes.
descending sorting on hash values
it seems sorted alphabetically. convert to numeric first.
h.sort_by {|_key, value| -value.to_f}
the minus sign could avoid the using of reverse
How to sort a Ruby Hash by number value?
No idea how you got your results, since it would not sort by string value... You should reverse a1
and a2
in your example
Best way in any case (as per Mladen) is:
metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" => 10 }
metrics.sort_by {|_key, value| value}
# ==> [["siteb.com", 9], ["sitec.com", 10], ["sitea.com", 745]]
If you need a hash as a result, you can use to_h
(in Ruby 2.0+)
metrics.sort_by {|_key, value| value}.to_h
# ==> {"siteb.com" => 9, "sitec.com" => 10, "sitea.com", 745}
Related Topics
Handling Exceptions Raised in a Ruby Thread
Rails Article Helper - "A" or "An"
How to Get a Particular Line from a File
How to Change Column Type in Heroku
How to Find Out Who Is Connected to Actioncable
Ruby Block to String Instead of Executing
How to Create a Nokogiri Case Insensitive Xpath Selector
How to Read a File from Bottom to Top in Ruby
Xpath Expression for Regex-Like Matching
Trying to Install Ruby-Filemagic on Snow Leopard Using Brew Rather Than Ports
Ruby-Debug19 on Ruby-1.9.3-Preview1
Rails - Redirecting Console Output to a File
How to Extract the Code from a Proc Object