0

I have an Array (test) with two nested hashes. What am trying to do is replace the Key value ("idea"=>"Hi") of the first hash (thing). But when i run the program it crashes and i haven't got an error message. I have tried a few variations, but the same results so I'm clearly missing a key step.

Thanks in advance for the help.

test=[thing={"idea"=>"Hi", "dumb"=>"test"}, thing2={"idea"=>"not sure", "dumb"=>"not"}]
puts test [0]

test=[0] [thing] ["idea"]="Bye"
puts test [0]
gets

1 Answer 1

1

You need to:

  • quote hash keys,
  • use => instead of = between hash keys and values,
  • put braces around the hashes,
  • remove an extra = in test=[0] [thing] ["idea"]:
test = [{'thing' => { 'idea'=>'Hi',         'dumb' => 'test' }},
        {'thing2' => {'idea' => 'not sure', 'dumb' => 'not'}}]
puts test[0] # {"thing"=>{"idea"=>"Hi", "dumb"=>"test"}}
test[0]['thing']['idea']='Bye'
puts test[0] # {"thing"=>{"idea"=>"Bye", "dumb"=>"test"}}


Also note that your original code as posted gives me an error, contrary to what you observed:

test=[thing={"idea"=>"Hi", "dumb"=>"test"}, thing2={"idea"=>"not sure", "dumb"=>"not"}]
puts test [0]

test=[0] [thing] ["idea"]="Bye" # Error: no implicit conversion of Hash into Integer (TypeError)

This error message should alert you that something wrong is going on with this line (or before). The error may look cryptic. But the proximal cause of it is that thing has been assigned to a hash before: thing={"idea"=>"Hi", "dumb"=>"test"}. And on this line the interpreter tries to use thing hash as an (integer) index into the array [0] - and fails to cast hash as integer. Note that the interpreter tries to treat [0] [thing] ["idea"]="Bye" as an assignment.

Long story short, make sure the error messages are displayed. Perhaps they are hidden, for example, by redirecting stderr to a file or /dev/null.

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

2 Comments

Hi Timur, thanks for your help! That makes makes sense.
@Guvna If this answer solves your problem, please accept this answer. This will increase both the answerer's and your reputation.

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.