1

I'd like to insert a hash into a specific location in an array. I have this:

arr = [
  {:key1=>"one", :key2=>"two", :key3=>"three"},
  {:key1=>"four", :key2=>"five", :key3=>"six"},
  {:key1=>"seven", :key2=>"eight", :key3=>"nine"}
]

and would like to insert this hash into the array

{:key1=>"---", :key2=>"---", :key3=>"---"}

So that the result is

arr = [
  {:key1=>"one", :key2=>"two", :key3=>"three"},
  {:key1=>"---", :key2=>"---", :key3=>"---"},  
  {:key1=>"four", :key2=>"five", :key3=>"six"},
  {:key1=>"seven", :key2=>"eight", :key3=>"nine"}
]

Can anyone help please

2
  • What you want to insert is not a hash, nor is it a valid Ruby object. Commented Apr 19, 2013 at 5:32
  • 1
    You wanted to do an insert, and Ruby Array has an insert method. All you had to do was refer the docs. Commented Apr 19, 2013 at 5:51

2 Answers 2

4

I think you should use the array insert method.

arr.insert(1, {:key1=>"---", :key2=>"---", :key3=>"---"} )

Check out the example here http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-insert

Sign up to request clarification or add additional context in comments.

Comments

1

arr.insert(1,{:key1=>"---", :key2=>"---", :key3=>"---"})

1 Comment

missing the closing parenthesis :)

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.