Ruby Hash交互与推送到数组
所以我要说我做了以下事情:
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 – “如果随后通过与散列条目不对应的密钥访问此散列,则返回的值取决于用于创建散列的新样式”.
在您的示例中,您尝试将某些内容推送到与不存在的键相关联的值上,因此您最终会改变最初用于构造哈希的相同匿名数组. 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. 您可能想要使用块形式:
例如: 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] } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |