Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is Hash ordered based on when the entry was inserted? #7593

Closed
xqyww123 opened this issue Mar 26, 2019 · 6 comments
Closed

Is Hash ordered based on when the entry was inserted? #7593

xqyww123 opened this issue Mar 26, 2019 · 6 comments

Comments

@xqyww123
Copy link
Contributor

Hi, everybody.

I just want to make sure whether Hash#keys or Hash#each returns entries in order based on when they were inserted. I found it's mentioned in Hash#key_index in document, and it looks like it's ordered viewing the code of key_index. But nothing mentioned in any other place about this, and the document of Set say Set based on Hash is unordered.

@xqyww123 xqyww123 changed the title Is Hash ordered? Is Hash ordered based on when the entry was inserted? Mar 26, 2019
@xqyww123
Copy link
Contributor Author

And more is it safe to insert new entry into Hash during the iteration of it, and will the new inserted entry be visited in the iteration?

@straight-shoota
Copy link
Member

  1. Key-value pairs in a Hash are sorted by insertion order.
  2. A Set by definition has no order. In practice, the items will be sorted by insertion order because of the implementation. But it's not guaranteed. If we change the implementation, this might not longer be true. Sets should always be considered unordered.
  3. It should be safe to add elements to any stdlib collection while enumerating it and newly added items should be enumerated as well.

We should use this issue to improve the documentation.

@asterite
Copy link
Member

For 2, a Set has an order. In theory it doesn't have one, but in practice it does. Same with Hash: in theory a mapping of keys from values isn't ordered, but in practice it is. And for example Ruby guarantees this (because they guarantee this through the implementation, and they won't suddenly change the implementation to unordered). We should do the same (guarantee that Set will stay ordered).

@straight-shoota
Copy link
Member

@asterite I can't find such a guarantee for Set in Ruby. The API docs explicitly state that it's an unordered collection and that the order of elements returned by #to_a is uncertain.

@asterite
Copy link
Member

@straight-shoota Oh, I guess it's ordered then because it's built on top of Hash. Nevermind.

@ysbaddaden
Copy link
Contributor

BTW: Hash wasn't ordered in Ruby 1.8.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants