问题
I have the following hash of countries;
COUNTRIES = {
'Albania' => 'AL',
'Austria' => 'AT',
'Belgium' => 'BE',
'Bulgaria' => 'BG',
.....
}
Now when I output the hash the values are not ordered alphabetically AL, AT, BE, BG ....but rather in a nonsense order (at least for me)
How can I output the hash having the values ordered alphabetically?
回答1:
Hashes have no internal ordering. You can't sort a Hash in place, but you can use the Hash#sort method to generate a sorted array of keys and values.
You could combine this with an Array#each to iterate over the Hash in your desired order.
So, an example would be:
COUNTRIES = {
'Albania' => 'AL',
'Austria' => 'AT',
'Belgium' => 'BE',
'Bulgaria' => 'BG',
}
COUNTRIES.sort {|a,b| a[1] <=> b[1]}.each{ |country| print country[0],"\n" }
回答2:
Using sort_by the whole thing becomes a bit more concise. Plus puts automatically adds the "\n":
COUNTRIES.sort_by { |k, v| v }.each { |country| puts country[0] }
来源:https://stackoverflow.com/questions/2455011/sort-by-values-from-hash-table-ruby