gpt4 book ai didi

ruby - 初始化哈希

转载 作者:数据小太阳 更新时间:2023-10-29 06:36:19 26 4
gpt4 key购买 nike

我经常写这样的东西:

a_hash['x'] ? a_hash['x'] += ' some more text' : a_hash['x'] = 'first text'

应该有更好的方法来做到这一点,但我找不到。

最佳答案

有两种方法可以为 Hash 创建初始值。

一种是将单个对象传递给Hash.new。这在很多情况下都很有效,尤其是当对象是一个卡住值时,但如果对象有内部状态,这可能会产生意想不到的副作用。由于同一对象在所有键之间共享而没有分配值,因此修改一个的内部状态将显示在所有键中。

a_hash = Hash.new "initial value"
a_hash['a'] #=> "initial value"
# op= methods don't modify internal state (usually), since they assign a new
# value for the key.
a_hash['b'] += ' owned by b' #=> "initial value owned by b"
# other methods, like #<< and #gsub modify the state of the string
a_hash['c'].gsub!(/initial/, "c's")
a_hash['d'] << " modified by d"
a_hash['e'] #=> "c's value modified by d"

另一种初始化方法是向Hash.new 传递一个 block ,每次为没有值的键请求值时调用该 block 。这允许您为每个键使用不同的值。

another_hash = Hash.new { "new initial value" }
another_hash['a'] #=> "new initial value"
# op= methods still work as expected
another_hash['b'] += ' owned by b'
# however, if you don't assign the modified value, it's lost,
# since the hash rechecks the block every time an unassigned key's value is asked for
another_hash['c'] << " owned by c" #=> "new initial value owned by c"
another_hash['c'] #=> "new initial value"

block 被传递了两个参数:要求值的散列和使用的键。这使您可以选择为该键分配一个值,以便每次给出特定键时都会显示相同的对象。

yet_another_hash = Hash.new { |hash, key| hash[key] = "#{key}'s initial value" }
yet_another_hash['a'] #=> "a's initial value"
yet_another_hash['b'] #=> "b's initial value"
yet_another_hash['c'].gsub!('initial', 'awesome')
yet_another_hash['c'] #=> "c's awesome value"
yet_another_hash #=> { "a" => "a's initial value", "b" => "b's initial value", "c" => "c's awesome value" }

这最后一种方法是我最常使用的方法。它还可用于缓存昂贵计算的结果。

关于ruby - 初始化哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2990812/

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