Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort hash by key, return hash in Ruby

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"=>1, "c"=>3, "b"=>2, "d"=>4}  Hash[h.sort] # => {"a"=>1, "b"=>2, "c"=>3, "d"=>4} 
like image 473
Vincent Avatar asked Dec 02 '10 20:12

Vincent


People also ask

How do I sort a hash key in Ruby?

If you want to access a Hash in a sorted manner by key, you need to use an Array as an indexing mechanism as is shown above. This works by using the Emmuerator#sort_by method that is mixed into the Array of keys. #sort_by looks at the value my_hash[key] returns to determine the sorting order.

What hash function does Ruby use?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.

How do I get the hash value in Ruby?

hash.fetch(key) { | key | block } Returns a value from hash for the given key. If the key can't be found, and there are no other arguments, it raises an IndexError exception; if default is given, it is returned; if the optional block is specified, its result is returned.


2 Answers

In Ruby 2.1 it is simple:

h.sort.to_h 
like image 168
Mark Thomas Avatar answered Oct 14 '22 23:10

Mark Thomas


Note: Ruby >= 1.9.2 has an order-preserving hash: the order keys are inserted will be the order they are enumerated. The below applies to older versions or to backward-compatible code.

There is no concept of a sorted hash. So no, what you're doing isn't right.

If you want it sorted for display, return a string:

"{" + h.sort.map{|k,v| "#{k.inspect}=>#{v.inspect}"}.join(", ") + "}" 

or, if you want the keys in order:

h.keys.sort 

or, if you want to access the elements in order:

h.sort.map do |key,value|   # keys will arrive in order to this block, with their associated value. end 

but in summary, it makes no sense to talk about a sorted hash. From the docs, "The order in which you traverse a hash by either key or value may seem arbitrary, and will generally not be in the insertion order." So inserting keys in a specific order into the hash won't help.

like image 40
Peter Avatar answered Oct 14 '22 23:10

Peter