If you want to access the values from the hash in a particular order, then sort the hash, allow Ruby to convert it to an array of arrays and use those to extract the values with their associated keys in the desired order:
h = {"a"=> 20, "b"=> 30 , "c" => 25}
sorted_values = h.sort_by{ |k,v| v } # => [["a", 20], ["c", 25], ["b", 30]]
sorted_values.each do |k, v|
puts "#{v} <= #{k}"
end
# >> 20 <= a
# >> 25 <= c
# >> 30 <= b
Why Ruby converts the hash key/value pairs to sub-arrays makes sense to me. The only reason I've ever figured out for sorting a hash is to access the values in a particular order and retain the mapping of keys and values, which the sub-arrays do.
Note: I'm using sort_by because it's faster when having to dig into structures or compute intermediate sorting values than sort. This particular use-case is probably not the best example since the hash is very simple, but most of my real-life examples end up having to dive in pretty deep and sort_by rules at that point.
Where is this all documented? It isn't. The documentation for Hash doesn't mention sort or sort_by which are inherited from Enumerable. Enumerable's documentation for sort and sort_by, while good, only refers to cases when an Array is being sorted. Learning that hashes are broken into key/value pairs then passed in comes from experience, it should be documented, which now can be a task you take on. Hint. Hint.
eachto iterate over it. That can all be short-circuited if you iterate over the returned array-of-arrays instead, which is already in the order desired. And the array-of-arrays confused you, leading to the question.{}.sort #=> []? Really? Currently we all slam into that particular wall, whether we read thesortorsort_bydocumentation. That the resulting array-of-arrays is more useful needs to be explained so people understand the logic and design-process, rather than think it's a random decision and come up with weird work-arounds.