2

I have a set of nested hashes. I would like to add the string "Assembly" to the array value associated with [:dennis_ritche][:languages]

def adding_to_dennis
    programmer_hash =
        {
        :grace_hopper => {
          :known_for => "COBOL",
          :languages => ["COBOL", "FORTRAN"]
        },
        :alan_kay => {
          :known_for => "Object Orientation",
          :languages => ["Smalltalk", "LISP"]
        },
        :dennis_ritchie => {
          :known_for => "Unix",
          :languages => ["C"]
        }
     }
        programmer_hash[:dennis_ritchie][:languages] << "Assembly"
end

This is the error I get no implicit conversion of Symbol into Integer"

2
  • 1
    This code works as-is. I'm not sure why you've wrapped it in a method, but perhaps that's the issue. Commented Nov 24, 2016 at 20:17
  • Yea i think it should work. I have to wrap it in a method to get it to pass a test in a learning environment. Commented Nov 24, 2016 at 20:18

1 Answer 1

1

I think the problem you're seeing is you're manipulating the hash inside the method and as a result are inadvertently returning the wrong thing. This method returns an Array because that's the last operation performed (<< on Array return the modified Array).

To fix it define a method that does the manipulation:

def add_to_hash(hash, programmer = :dennis_ritchie, language = 'Assembly')
  hash[programmer][:languages] << language
end

Make that independent of the definition:

programmer_hash =
    {
    :grace_hopper => {
      :known_for => "COBOL",
      :languages => ["COBOL", "FORTRAN"]
    },
    :alan_kay => {
      :known_for => "Object Orientation",
      :languages => ["Smalltalk", "LISP"]
    },
    :margaret_hamilton => {
      :known_for => "Apollo Program",
      :languages => ["Assembly"]
    },
    :dennis_ritchie => {
      :known_for => "Unix",
      :languages => ["C"]
    }
 }

Then call it to manipulate the hash:

add_to_hash(programmer_hash)

The programmer_hash structure is then updated.

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

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.