Would this be the best way to sort a hash and return Hash object (instead of Array):
h = {\"a\"=>1, \"c\"=>3, \"b\"=>2, \"d\"=>4}
# => {\"a\"=
You gave the best answer to yourself in the OP: Hash[h.sort]
If you crave for more possibilities, here is in-place modification of the original hash to make it sorted:
h.keys.sort.each { |k| h[k] = h.delete k }
I liked the solution in the earlier post.
I made a mini-class, called it class AlphabeticalHash
. It also has a method called ap
, which accepts one argument, a Hash
, as input: ap variable
. Akin to pp (pp variable
)
But it will (try and) print in alphabetical list (its keys). Dunno if anyone else wants to use this, it's available as a gem, you can install it as such: gem install alphabetical_hash
For me, this is simple enough. If others need more functionality, let me know, I'll include it into the gem.
EDIT: Credit goes to Peter, who gave me the idea. :)
I've always used sort_by
. You need to wrap the #sort_by
output with Hash[]
to make it output a hash, otherwise it outputs an array of arrays. Alternatively, to accomplish this you can run the #to_h
method on the array of tuples to convert them to a k=>v
structure (hash).
hsh ={"a" => 1000, "b" => 10, "c" => 200000}
Hash[hsh.sort_by{|k,v| v}] #or hsh.sort_by{|k,v| v}.to_h
There is a similar question in "How to sort a Ruby Hash by number value?".
Sort hash by key, return hash in Ruby
With destructuring and Hash#sort
hash.sort { |(ak, _), (bk, _)| ak <=> bk }.to_h
Enumerable#sort_by
hash.sort_by { |k, v| k }.to_h
Hash#sort with default behaviour
h = { "b" => 2, "c" => 1, "a" => 3 }
h.sort # e.g. ["a", 20] <=> ["b", 30]
hash.sort.to_h #=> { "a" => 3, "b" => 2, "c" => 1 }
Note: < Ruby 2.1
array = [["key", "value"]]
hash = Hash[array]
hash #=> {"key"=>"value"}
Note: > Ruby 2.1
[["key", "value"]].to_h #=> {"key"=>"value"}
@ordered = {}
@unordered.keys.sort.each do |key|
@ordered[key] = @unordered[key]
end
ActiveSupport::OrderedHash is another option if you don't want to use ruby 1.9.2 or roll your own workarounds.