开发者

Ruby, Append value to existing value for key value pair in hash table

开发者 https://www.devze.com 2023-04-05 10:41 出处:网络
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 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 appe开发者_JAVA技巧nd 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)


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])
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号