Ruby,将值附加到哈希表中键值对的现有值

发布于 2024-12-05 13:07:26 字数 503 浏览 6 评论 0原文

我有一个嵌套哈希表。

如果我写,

 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月静好 2024-12-12 13:07:26

由于 value[value.size] 计算结果为 nil,value[value.size][0] = Title3 计算结果为 nil[0] = Title3,这就是您收到错误的原因。相反,您想要做的是将包含 Title3 和 name3 的数组附加到 value,因此:

value[value.size] = [Title3, name3]

或者更好地使用方法 push 而不是 value[value.size] =

value.push([Title3, name3])

Since value[value.size] evaluated to nil, value[value.size][0] = Title3 evaluates to nil[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:

value[value.size] = [Title3, name3]

Or better use the method push instead of value[value.size] =:

value.push([Title3, name3])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文