3 ms·
I actually found it more interesting that Ruby hashmaps ("hashes" :S) preserve insertion order and guarantee predictable insertion. I was taught to never trust
by nvader 11y ago
I actually found it more interesting that Ruby hashmaps ("hashes" :S) preserve insertion order and guarantee predictable insertion.
I was taught to never trust the ordering returned by iterating over keys of hashmaps because it can be a source of bugs as you move between architectures or interpreters. If you need a guaranteed ordering, keep (and pay for) the appropriate auxiliary data structure.
Has this lesson become obsolete? Perhaps "computers are fast" so now Ruby can afford to use ordered hashmaps everywhere. On the other hand, I know Go chose to randomize iteration order of keys on purpose so developers cannot rely on them.
- bradhe 11y agoIt's a side effect of their implementation and you should continue to not trust their default ordering.
- nvader 11y agoIt appears that since Ruby 1.9 they guarantee insertion order: http://ruby-doc.org/core-2.3.0/Hash.html http://ruby-doc.org/core-2.3.0/Hash.html I guess there are two approaches to solving the problem of people using your data structures the wrong way. Edit: wrong link
- ghayes 11y agoAs opposed to Go [0] > When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. Since Go 1 the runtime randomizes map iteration order, as programmers relied on the stable iteration order of the previous implementation. [0] https://blog.golang.org/go-maps-in-action https://blog.golang.org/go-maps-in-action
- tom-lord 11y agoYes, you can. Ordering has been guaranteed since ruby v1.9, very much intentionally. The implementation of a ruby hash is now as a doubly linked list [0]. This has inevitably caused a slight performance hit, but the benefits far outweigh the cost IMO. [0] https://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/ https://www.igvita.com/2009/02/04/ruby-19-internals-ordered-...