Does Set in Ruby always preserve insertion order?

2019-04-21 20:00发布

问题:

i.e., is Ruby's Set equivalent to Java's LinkedHashSet?

回答1:

In Ruby 1.9: yes. In Ruby 1.8: probably not.

Set uses a Hash internally; and since hashes are insertion-ordered in 1.9, you're good to go!

As mu is too short points out, this is an implementation detail and could change in the future (though unlikely). Thankfully, the current implementation of Set is pure ruby, and could be adapted into an OrderedSet in the future if you like



标签: ruby set