作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
{} -6ren">
假设我执行以下操作:
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"]}
我对此感到惊讶。几个问题:
最佳答案
阅读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/
我是一名优秀的程序员,十分优秀!