Hash sorting alphabetiacly in ruby -
i have following hash.
h = { "31d2fcd5-aec0-438d-895c-806fd0358c23"=>{"name"=>"q", 'database'=>'mysql'}, "69a05dea-d767-44b7-b40c-f76d0d12f8c1"=>{"name"=>"qwerty", 'database'=>'h2'}, "69a05dea-d767-44b7-b40c-f76d0d121993"=>{"name"=>"b", 'database'=>'postgresql'}, "69a05dea-d767-44b7-b40c-f76d0d121994"=>{"name"=>"b", 'database'=>'oracle'}, "69a05dea-d767-44b7-b40c-f76d0d121995"=>{"name"=>"apple", 'database'=>'sqlite3'}, "69a05dea-d767-44b7-b40c-f76d0d521996"=>{"name"=>"a", 'database'=>'mariadb'}, "69a05dea-d767-44b7-b40c-f76d0d1k1996"=>{"name"=>"a", 'database'=>'mongodb'} }
after sorting see in following form
h = { "31d2fcd5-aec0-438d-895c-806fd0358c23"=>{"name"=>"a", 'database'=>'mariadb'}, "69a05dea-d767-44b7-b40c-f76d0d12f8c1"=>{"name"=>"a", 'database'=>'mongodb'}, "69a05dea-d767-44b7-b40c-f76d0d121993"=>{"name"=>"apple", 'database'=>'sqlite3'}, "69a05dea-d767-44b7-b40c-f76d0d121994"=>{"name"=>"b", 'database'=>'postgresql'}, "69a05dea-d767-44b7-b40c-f76d0d121995"=>{"name"=>"b", 'database'=>'oracle'}, "69a05dea-d767-44b7-b40c-f76d0d521996"=>{"name"=>"q", 'database'=>'mysql'}, "69a05dea-d767-44b7-b40c-f76d0d1k1996"=>{"name"=>"qwerty", 'database'=>'h2'} }
thanks in advance.
short answer: can't. see docs hashes in ruby 1.8.7:
the order in traverse hash either key or value may seem arbitrary, , not in insertion order.
in ruby 1.8.7 hashes not ordered. not guaranteed order matches order in keys inserted (like in ruby 1.9+).
that said: have use different data structure, array example. arrays can sorted first value , keep order.
btw: ruby 1.8.7 outdated more many years (its successor ruby 1.9 released 6 years ago). ruby 1.8.7 missing interesting features, doesn't security updates anymore , many gems dropped support old version. advise update @ least ruby 2.2+
Comments
Post a Comment