Ruby/Rails nested hash myhash["key1"]["childkey"] - NoMethodError
Hey guys so I'm trying to construct some json based on a form submission. My json needs to be something like this (truncated for simplicity):
{"id":0,"creditCard":{"address":{"state":"AZ"}}}
Basically I'm trying to do it like this:
json_hash = Hash.new
json开发者_如何学C_hash["id"] = 0
json_hash["creditCard"]["address"]["state"] = "test"
json_hash.to_json
But its throwing this errror:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
At the 3rd line in the example given (the deeply nested thing). Do ruby hashes work like this? Or are there extra steps I need to take?
Because at the third line you're evaluating a json_hash['creditCard']
which is nil
, then it has no method []
.
You can build an hash like that using
json_hash = { "id" => 0,"creditCard" => { "address" => {"state" => "AZ"}}}
and it has the given format.
Thats a short syntax, to specify the fact that what you want in json_hash
it's NOT a single hash. It is an hash which has the value 0 in its "id"
key, then in its "creditCard"
it stores another hash which contains another hash (i.e. {"state" => "AZ"}
) in its "address"
key.
Look at this pry transcript:
pry(main)> json_hash = { "id" => 0,"creditCard" => { "address" => {"state" => "AZ"}}}
=> {"id"=>0, "creditCard"=>{"address"=>{"state"=>"AZ"}}}
pry(main)> json_hash.object_id
=> 2175368520
pry(main)> json_hash['creditCard'].object_id
=> 2175368560
pry(main)> json_hash['creditCard']['address'].object_id
=> 2175368600
all these values have different object_id
so they are not the same thing, neither property of the same thing.
精彩评论