7

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  

3 Answers 3

12

<< 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 
Sign up to request clarification or add additional context in comments.

5 Comments

He says that he wants multi-dimensional array
Thanks, the code you outlined for the two-dimensional array worked
@Thomas, how did you do that there is no "edited" mark after the answer?
Good question. I just hit the 'edit' link. Not sure why it doesn't appear. Maybe because it was quickly after I posted it? Maybe because I'm the original poster? Maybe because it didn't have any votes yet?
can you save @array to active record column?
3

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"] 

2 Comments

Thanks, good to see that there are different ways. I had to run array = [] first though before inserting anything in the example above, otherwise it would return undefined method <<' for nil:NilClass
Yes. array = [] is the same as array = Array.new. One usually declares an array variable before inserting into it.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.