Sort by values from hash table - Ruby

 ̄綄美尐妖づ 提交于 2020-01-02 09:58:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!