简体   繁体   English

从红宝石哈希中的键访问值

[英]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] . 要访问_id的值,我认为命令应该只是test。[key]。 But I run test.[_id] and I keep getting errors. 但是我运行了test。[_ id],并且不断出错。 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 . 否则,您将必须访问arr.[](0)类的数组,并添加1.+(2) ,等等。为了使其更加“自然”,Ruby添加了语法糖,从而消除了对的需求. when calling methods with certain names (such as [] , + , etc.). 当使用某些名称(例如[]+等)调用方法时。

Secondly, you don't have a variable called _id . 其次,您没有名为_id的变量。 You need to pass it as a string. 您需要将其作为字符串传递。

puts test["_id"]

您应该改用test["_id"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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