Ruby:将哈希插入数组? [英] Ruby: Insert hash into array?

查看:49
本文介绍了Ruby:将哈希插入数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个哈希值插入到一个数组中,如下所示:如何在 ruby​​ 中制作动态多维数组?.出了什么问题?

I'm trying to insert a hash into an array, following this example: How to make dynamic multi-dimensional array in ruby?. What went wrong?

@array = Array.new
test1 = {"key1" => "value1"}
test2 = {"key2" => "value2"}
test3 = {"key3" => "value3"}            
@array.push(0)
@array[0] << test1
# ERROR: can't convert Hash into Integer    
@array[0] << test2    
@array.push(1)
@array[1] << test2
@array[1] << test3  

推荐答案

<< 追加到数组中,与 push 相同,所以只需:

<< appends to the array, the same as push, so just do:

@array << test1

或者,如果您想覆盖特定元素,请说0:

Or, if you want to overwrite a particular element, say 0:

@array[0] = test1

<小时>

或者你真的想要一个二维数组,比如 @array[0][0]["key1"] == "value1"?在这种情况下,您需要先将空数组插入正确的位置,然后再尝试附加到它们:


Or do you actually want a two-dimensional array, such that @array[0][0]["key1"] == "value1"? In that case, you need to insert empty arrays into the right place before you try to append to them:

@array[0] = []
@array[0] << test1
@array[0] << test2    
@array[1] = []
@array[1] << test2
@array[1] << test3 

这篇关于Ruby:将哈希插入数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆