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

非 Y 不嫁゛ 提交于 2019-12-01 11:09:20

问题


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 {|a, b| a[1] <==> b[1]}
#sorted_by_values is an array of array, it's no longer a hash!
sorted_by_values.keys.join ',' 

my workaround is to make method to_hash for Array class.

class Array
  def to_hash(&block)
    Hash[*self.collect { |k, v|
      [k, v]
    }.flatten]
  end
end

I can then do the following:

sorted_by_values.to_hash.keys.join ','

Is there a better way to do this?


回答1:


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 ','


来源:https://stackoverflow.com/questions/489139/ruby-1-8-hashsort-not-return-hash-but-array-better-way-to-do-this

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