1
在Ruby 1.8的一些情況。如果我有一個哈希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 ','
我的解決方法是使數組類方法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 ','
有沒有更好的方式來做到這一點?
請注意,哈希按照Ruby 1.9中的鍵放置順序排序。 – 2011-03-24 17:50:22