Ruby 1.8:散列#sort不返回散列但是数组(更好的方法是这样做吗?)

在Ruby 1.8的某些场景中。 如果我有哈希

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

我的解决方法是为Array类创建方法to_hash

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

然后我可以做以下事情:

 sorted_by_values.to_hash.keys.join ',' 

有一个更好的方法吗?

根据定义,哈希是无序的。 没有排序哈希这样的东西。 你最好的选择可能是使用collect从排序数组中提取密钥,然后对结果进行连接

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