我正在尝试将哈希插入到数组中,遵循以下示例:How to make dynamic multi-dimensional array in ruby?。出了什么问题?
@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
答案 0 :(得分:9)
<<
附加到数组,与push
相同,所以只需执行:
@array << test1
或者,如果您想覆盖特定元素,请说0
:
@array[0] = test1
或者你真的想要一个二维数组,例如@array[0][0]["key1"] == "value1"
?在这种情况下,您需要在尝试追加它们之前将空数组插入正确的位置:
@array[0] = []
@array[0] << test1
@array[0] << test2
@array[1] = []
@array[1] << test2
@array[1] << test3
答案 1 :(得分:2)
有许多方法可以插入Ruby数组对象。这是一些方法。
1.9.3p194 :006 > array = []
=> []
1.9.3p194 :007 > array << "a"
=> ["a"]
1.9.3p194 :008 > array[1] = "b"
=> "b"
1.9.3p194 :009 > array.push("c")
=> ["a", "b", "c"]
1.9.3p194 :010 > array_2 = ["d"]
=> ["d"]
1.9.3p194 :011 > array = array + array_2
=> ["a", "b", "c", "d"]
1.9.3p194 :012 > array_3 = ["e"]
=> ["e"]
1.9.3p194 :013 > array.concat(array_3)
=> ["a", "b", "c", "d", "e"]
1.9.3p194 :014 > array.insert("f")
=> ["a", "b", "c", "d", "e"]
1.9.3p194 :015 > array.insert(-1,"f")
=> ["a", "b", "c", "d", "e", "f"]
答案 2 :(得分:0)
@array[0] << test1
表示0 << { "key1" => "value1" }
,这是尝试通过哈希进行位移0
。 Ruby无法将哈希值转换为整数以实现此目的,这就是您收到该错误消息的原因。