如何访问这个info_config [:hash] [key]

时间:2014-07-23 12:19:05

标签: ruby-on-rails-4 rails-console

我有一个文件info.yml,有这样的信息

"email1@gmail.com":
      ame: "Paul"
      from: "VISA-PG-Credit Card Acquittal-"
      project: "001-Admin"
      entity: "01-HTW (Los Angeles)"

"email2@gmail.com"
     name: "Bill"
     from: "VISA-PG-Company"
     project: "005-Admin"
     entity: "01-HTW (Panama)"

现在我正尝试从控制台访问此信息。当我尝试这个

>>INFO_CONFIG[:"email1@gmail.com"]["project"]

它给了我正确的结果“001-Admin” 但如果我试试这个

>>sender = "email1@gmail.com"

>>INFO_CONFIG[:sender]["project"]

它给了我以下错误:

NoMethodError: undefined method `[]' for nil:NilClass

我的语法有什么问题?

2 个答案:

答案 0 :(得分:0)

您应该像这样使用to_sym

INFO_CONFIG[sender.to_sym]["project"]

似乎做你想做的事:

"email1@gmail.com".to_sym #=> :"email1@gmail.com"

答案 1 :(得分:-1)

您传递符号:sender作为数组键,但您希望将电子邮件地址(作为字符串)作为键:

sender = "email1@gmail.com"
INFO_CONFIG[sender]['project']