gpt4 book ai didi

ruby-on-rails - 我们可以写一个没有哈希类的哈希吗?

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

为了这个问题,我们假设我们在 Ruby 中没有 hash 类。

是否可以在不使用 Ruby 中的 hash class 的情况下创建 hash?或者,如果我们没有散列概念,我们可能会称它为关联数组

最佳答案

虽然可以使用数组来模拟哈希的行为,但性能会受到影响:

require 'fruity'

CHARS = ('a' .. 'z').to_a
ARY = CHARS.zip(CHARS)
HASH = ARY.to_h

compare do
_assoc_a { ARY.assoc('a') }
_hash_a { HASH['a'] }
_hash_m { HASH['m'] }
_assoc_m { ARY.assoc('m') }
_assoc_z { ARY.assoc('z') }
_hash_z { HASH['z'] }
end
# >> Running each test 32768 times. Test will take about 3 seconds.
# >> _hash_m is similar to _hash_z (results differ: m vs z)
# >> _hash_z is similar to _hash_a (results differ: z vs a)
# >> _hash_a is faster than _assoc_a by 2x ± 1.0 (results differ: a vs ["a", "a"])
# >> _assoc_a is faster than _assoc_m by 5x ± 1.0 (results differ: ["a", "a"] vs ["m", "m"])
# >> _assoc_m is faster than _assoc_z by 2x ± 0.1 (results differ: ["m", "m"] vs ["z", "z"])

进行反向查找,从第二个元素到第一个,或者从值到键:

compare do
_rassoc_a { ARY.rassoc('a') }
_hash_rassoc_a { HASH.rassoc('a') }
_rassoc_m { ARY.rassoc('m') }
_hash_rassoc_m { HASH.rassoc('m') }
_rassoc_z { ARY.rassoc('z') }
_hash_rassoc_z { HASH.rassoc('z') }
end
# >> Running each test 32768 times. Test will take about 4 seconds.
# >> _rassoc_a is faster than _hash_rassoc_a by 2x ± 1.0
# >> _hash_rassoc_a is faster than _rassoc_m by 3x ± 1.0 (results differ: ["a", "a"] vs ["m", "m"])
# >> _rassoc_m is similar to _hash_rassoc_m
# >> _hash_rassoc_m is similar to _rassoc_z (results differ: ["m", "m"] vs ["z", "z"])
# >> _rassoc_z is similar to _hash_rassoc_z

对我来说,将散列反向查找到 key 会更慢,因为散列并未针对此类事情进行优化。如果我需要这样做,我会尝试创建一个单独的哈希来反转键和值,然后使用它来进行反向查找:

hash = {'a' => 1, 'b' => 2}
reversed_hash = hash.invert # => {1=>"a", 2=>"b"}

如果值是一个数组或值不是唯一的,这会中断,有时生成的键使用起来不是很方便。

关于ruby-on-rails - 我们可以写一个没有哈希类的哈希吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36291185/

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