加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby Hash交互与推送到数组

发布时间:2020-12-17 03:49:01 所属栏目:百科 来源:网络整理
导读:所以我要说我做了以下事情: 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","HJK
所以我要说我做了以下事情:

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方式是什么?我有一个哈希,一个键和一个值,我希望最终在与键相关联的数组中.如何在第一次将与键关联的数组中的值推送到哈希中.在以后的所有密钥使用中,我只想添加到数组中.

解决方法

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

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.

您可能想要使用块形式:

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] }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读