1

I am new in Ruby and I wanna add a block of hash to the top of the programmer_hash:

def adding_matz
    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"]
    }
 }
end

This is what I want to add to the top of programmer_hash hash:

:yukihiro_matsumoto => {
    :known_for => "Ruby",
     :languages => ["LISP", "C"]
}

I have added the code below at the end of the method:

programmer_hash[:yukihiro_matsumoto] = [:known_for['Ruby']]
programmer_hash[:yukihiro_matsumoto][:languages] = 'LISP'
programmer_hash[:yukihiro_matsumoto][:languages] = 'C'

It worked pretty well, but I want to do all of this in one line, but nothing comes out right. I will appreciate your help.

1
  • 2
    "I have added the code below [...] It worked pretty well" – I doubt so. :known_for['Ruby'] returns nil, so the first line would assign [nil] to the key :yukihiro_matsumoto. The second line would then result in an error. Commented Aug 20, 2019 at 8:01

2 Answers 2

2

Assign a new hash to :yukihiro_matsumoto key in the main hash:

programmer_hash[:yukihiro_matsumoto] = { 
  known_for: 'Ruby'
  languages: ['LISP', 'C']
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can merge two hashes. Standard docs for merge!

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

Then you have your another hash like below

another_hash = { 
    :yukihiro_matsumoto => {
        :known_for => "Ruby",
         :languages => ["LISP", "C"]
    }
}

Then you can merge them by -

programmer_hash.merge!(another_hash)

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.