Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Insert hash into array?

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  
like image 737
migu Avatar asked Oct 05 '12 21:10

migu


2 Answers

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

@array << test1

Or, if you want to overwrite a particular element, say 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] = []
@array[0] << test1
@array[0] << test2    
@array[1] = []
@array[1] << test2
@array[1] << test3 
like image 115
Thomas Avatar answered Oct 03 '22 23:10

Thomas


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

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"] 
like image 45
Martin Velez Avatar answered Oct 04 '22 00:10

Martin Velez