简体   繁体   中英

Accessing a value from a key in a ruby hash

So I have a hash:

test =  {"_id"=>"5516c07ba520e0066c9ac53c", "accounts"=>[], "address"=>{"zip"=>"45245", "state"=>" Ohio", "city"=>"Cincinnati", "street"=>"3320 Wagner Road"}, "first_name"=>"Black", "last_name"=>"Bart"}

and I'm just playing around in the ruby console. To access the value at _id, I thought the command should just be test.[key] . But I run test.[_id] and I keep getting errors. This seems pretty simple, but I'm missing some syntax.

Firstly, there's no . . Otherwise, you would have to access arrays like arr.[](0) , add numbers like 1.+(2) , etc. To make this more "natural," Ruby adds syntaxic sugar that removes the need for the . when calling methods with certain names (such as [] , + , etc.).

Secondly, you don't have a variable called _id . You need to pass it as a string.

puts test["_id"]

您应该改用test["_id"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM