Ruby 1.8: Hash#sort not return hash but array (better way to do this?)

后端 未结 1 1778
天命终不由人
天命终不由人 2021-01-15 22:38

In some scenario of Ruby 1.8. If I have a hash

# k is name, v is order
foo = { \"Jim\" => 1, \"bar\" => 1, \"joe\" => 2}
sorted_by_values = foo.sort         


        
1条回答
  •  逝去的感伤
    2021-01-15 23:32

    Hashes are unordered by definition. There can be no such thing as a sorted Hash. Your best bet is probably to extract the keys from the sorted array using collect and then do a join on the result

    sortedByValues = foo.sort {|a, b| a[1] <==> b[1]}
    sortedByValues.collect { |a| a[0] }.join ','
    

    0 讨论(0)
提交回复
热议问题