{} -6ren">
gpt4 book ai didi

Ruby 哈希与推送到数组的交互

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

假设我执行以下操作:

lph = Hash.new([])       #=> {}
lph["passed"] << "LCEOT" #=> ["LCEOT"]
lph #=> {} <-- Expected that to have been {"passed" => ["LCEOT"]}
lph["passed"] #=> ["LCEOT"]
lph["passed"] = lph["passed"] << "HJKL"
lph #=> {"passed"=>["LCEOT", "HJKL"]}

我对此感到惊讶。几个问题:

  1. 为什么直到我将第二个字符串插入数组后它才被设置?后台发生了什么?
  2. 从本质上讲,更惯用的 ruby​​ 方式是什么?我有一个散列、一个键和一个值,我想在与键关联的数组中结束。我如何第一次将与键关联的数组中的值推送到哈希中。在 key 的所有 future 使用中,我只想添加到数组中。

最佳答案

阅读Ruby Hash.new documentation仔细 - “如果此散列随后被与散列条目不对应的键访问,则返回的值取决于用于创建散列的 new 的样式”。

new(obj) → new_hash

...If obj is specified, this single object will be used for all default values.

在您的示例中,您试图将某些内容推送到与不存在的键关联的值上,因此您最终会改变最初用于构造哈希的相同匿名数组。

the_array = []
h = Hash.new(the_array)
h['foo'] << 1 # => [1]
# Since the key 'foo' was not found
# ... the default value (the_array) is returned
# ... and 1 is pushed onto it (hence [1]).
the_array # => [1]
h # {} since the key 'foo' still has no value.

您可能想使用 block 形式:

new { |hash, key| block } → new_hash

...If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block’s responsibility to store the value in the hash if required.

例如:

h = Hash.new { |hash, key| hash[key] = [] } # Assign a new array as default for missing keys.
h['foo'] << 1 # => [1]
h['foo'] << 2 # => [1, 2]
h['bar'] << 3 # => [3]
h # => { 'foo' => [1, 2], 'bar' => [3] }

关于Ruby 哈希与推送到数组的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22814932/

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