在 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
为 Array 类制作方法。
class Array
def to_hash(&block)
Hash[*self.collect { |k, v|
[k, v]
}.flatten]
end
end
然后我可以执行以下操作:
sorted_by_values.to_hash.keys.join ','
有一个更好的方法吗?