3 ms·
A few random thoughts about Ruby's traditional unordered Hash: The Hash#keys method should have returned a Set, not an Array. That way no one would have been b
by ewiethoff 18y ago
A few random thoughts about Ruby's traditional unordered Hash:
The Hash#keys method should have returned a Set, not an Array. That way no one would have been baffled by the lack of predictable order. But, unfortunately, Set is not a built-in class. Hence, Hash#keys has to return an Array.
Since Rails came out, there's been, I think, an ever increasing use of Symbols as Hash keys. If you want to examine your Hash in a specific order--perhaps in a test--it's tempting to sort the Array of keys. But there's no Symbol#<=> method. Therefore, an Array of Symbols cannot be sorted (without monkey patching).
If, for whatever reason, you create a Hash whose keys are of various types, the keys are probably not sortable. Hence, there's no way to examine its contents in a predictable order.
A few thoughts about the new ordered Hash:
Personally, I see no need for the built-in Hash to be ordered. I'm so accustomed to thinking of hashes as unordered. And, because I don't have Ruby 1.9, I don't use the newfangled hashy syntax for passing parameters.
But one of the commenters (Radarek) points out something about parameter passing. He/she says, "It's another big + for ordered hashes because they are used as replacement for named parameters [in Ruby 1.9]." He/she mentions a project in which a method must process its keyword parameters in the order they were given.
The thought of trying to process keyword parameters in the order given is very jarring to my old-fashioned Ruby brain, and to my Python brain. Yet, evidently, someone out there wants to do this without telling the client to pass an Array of Arrays.
So I wonder what the major use case is for the predictable ordering of the built-in Hash. Perhaps it's for ease of examining and comparing Hashes in tests? Perhaps it's for processing keyword parameters in a specific order when they're passed using spiffy syntax? What?