Ruby 1.8: Hash # sort non restituisce hash ma array (modo migliore per farlo?)
Domanda
In alcuni scenari di Ruby 1.8. Se ho un 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 ','
la mia soluzione è di rendere il metodo to_hash
per la classe Array.
class Array
def to_hash(&block)
Hash[*self.collect { |k, v|
[k, v]
}.flatten]
end
end
Posso quindi fare quanto segue:
sorted_by_values.to_hash.keys.join ','
C'è un modo migliore per farlo?
Soluzione
Gli hash non sono ordinati per definizione. Non può esistere un hash ordinato. La soluzione migliore è probabilmente estrarre le chiavi dall'array ordinato usando raccogliere e quindi unire il risultato
sortedByValues = foo.sort {|a, b| a[1] <==> b[1]}
sortedByValues.collect { |a| a[0] }.join ','
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow