Ruby:将哈希插入数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12754563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:50:48  来源:igfitidea点击:

Ruby: Insert hash into array?

ruby-on-railsruby

提问by migu

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?

我正在尝试将一个散列插入到一个数组中,按照这个例子: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  

回答by Thomas

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

<<附加到数组,与 相同push,所以只需执行以下操作:

@array << test1

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

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

@array[0] = test1


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][0]["key1"] == "value1"吗?在这种情况下,您需要在尝试附加到空数组之前将空数组插入到正确的位置:

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

回答by Martin Velez

There are many ways to insert into a Ruby array object. Here are some ways.

有很多方法可以插入到 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"] 

回答by cdesrosiers

@array[0] << test1in this context means 0 << { "key1" => "value1" }, which is an attempt to bitshift 0by a hash. Ruby cannot convert a hash into an integer to make this happen, which is why you are getting that error message.

@array[0] << test1在这种情况下意味着0 << { "key1" => "value1" },这是0通过哈希进行位移的尝试。Ruby 无法将散列转换为整数来实现这一点,这就是您收到该错误消息的原因。