Ruby,将值附加到哈希表中键值对的现有值
我有一个嵌套哈希表。
如果我写,
json.each{|key, value|
puts value;
puts;
puts value[x];
puts;
puts value[x][0];
}
我会得到类似于
Title1 的结果
姓名1
标题2
姓名2
标题1
name1
Title1
我想要的是能够做一些类似的事情,
value[value.size][0] = Title3;
value[value.size][1] = name3;
以便将其附加到新集合的值的末尾 我刚刚所做的抛出了未定义的方法 '[]=' 所以我想知道 如果有人可以帮助我以这种方式或其他方式附加值 这样我就可以增加与同一键关联的值的数量,同时 保持它们与其关联的顺序。 (对于我记录 json 值时很重要)
I have a nested hash table.
If i write
json.each{|key, value|
puts value;
puts;
puts value[x];
puts;
puts value[x][0];
}
I get a result along the lines of
Title1
name1
Title2
name2
Title1
name1
Title1
What I would like is be able to do something along the lines of
value[value.size][0] = Title3;
value[value.size][1] = name3;
so that this appends to the end of the values a new set however
what i just did throws undefined method '[]=' so I was wondering
if anyone could help me to append values either this way or some other way
so that i can increase the amount of values associated to the same key whilst
maintaining the order in which they are associated with it.
(Important for when I am logging the json values)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于
value[value.size]
计算结果为 nil,value[value.size][0] = Title3
计算结果为nil[0] = Title3
,这就是您收到错误的原因。相反,您想要做的是将包含 Title3 和 name3 的数组附加到 value,因此:或者更好地使用方法
push
而不是value[value.size] =
:Since
value[value.size]
evaluated to nil,value[value.size][0] = Title3
evaluates tonil[0] = Title3
, which is why you get the error you do. What you want to do instead is to append an array containing Title3 and name3 to value, so:Or better use the method
push
instead ofvalue[value.size] =
: