gpt4 book ai didi

ruby - "Hashes enumerate their values in the order that the corresponding keys were inserted."

转载 作者:数据小太阳 更新时间:2023-10-29 07:55:01 25 4
gpt4 key购买 nike

来自 http://ruby-doc.org/core-2.4.0/Hash.html#method-i-each 的 ruby​​ 文档:

Hashes enumerate their values in the order that the corresponding keys were inserted.

通常,我希望以随机顺序枚举哈希值(以任意语言)。

ruby 如何跟踪插入顺序?除了哈希桶之外,它是否在键之间保留一个链表?我想这会非常简单,但我真的很惊讶(以一种好的方式)他们首先做到了。

最佳答案

是的,它有一个链表。这可以在不损害典型哈希表的典型 O(1) 分摊最坏情况步骤复杂性保证的情况下完成,因为使链表昂贵的所有操作(例如删除元素)都与需要遍历列表有关找到一个元素,但在这种特殊情况下,“查找”部分可以通过使用哈希表查找来缩短。

如果您对 Ruby 实现的内部结构感兴趣,我建议您阅读 Rubinius 源代码;它比 YARV 更简洁易读,而且它是用 Ruby 编写的,您可能已经熟记这种语言。 Rubinius 的 Hash 类在 core/hash.rb 中实现.请注意,当前版本的 Rubinius 使用 Hash Array Mapped Trie (HAMT) ,这与YARV使用的简单传统哈希表明显不同,但与附加链表的使用无关。如果你真的想要,你可以看看 older version仍然有传统的哈希表。

关于ruby - "Hashes enumerate their values in the order that the corresponding keys were inserted.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42668922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com