Josh Pann
Josh Pann

Reputation: 53

Add string to array nested inside of hash

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"

Upvotes: 2

Views: 269

Answers (1)

tadman
tadman

Reputation: 211560

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.

Upvotes: 1

Related Questions