首页 > 解决方案 > ruby 以变量为键访问哈希

问题描述

我有一个关于哈希访问的简单(我认为)问题。我有以下哈希(获取表单 yml 文件)

 {
   "all"=>   {
      "children"=> {
         "TSL-PCM-126"=>    {
            "children"=>  {
               "my_host-TSL-PCM-126"=> {
                  "hosts"=>   {
                     "TSF-W01"=> {
                        "ip"=>"192.168.0.201"
                     }
                  }
               }
            }
          }
      }
   }
}

我将主机名存储为变量

my_pc="#{`hostname`}" ==> my_pc="TSL-PCM-126"

我想访问正确的值,但使用 my_pc 变量作为键...

(库存 = 我的文件的 Yaml 加载)

puts inventory["all"]["children"] ==> Work
puts inventory["all"]["children"]["TSL-PCM-126"] ==> Work 
puts inventory["all"]["children"]["#{my_pc}"] ==> NOK :( 

标签: rubyhash

解决方案


OP编辑后,使用

my_pc = `hostname`.strip

避免字符串中的换行符。

这确实按预期工作,

> my_pc
 => "TSL-PCM-126" 
> puts inventory["all"]["children"]["#{my_pc}"]
{"children"=>{"my_host-TSL-PCM-126"=>{"hosts"=>{"TSF-W01"=>{"ip"=>"192.168.0.201"}}

您不需要字符串插值:

> inventory["all"]["children"][my_pc]
=> {"children"=>{"my_host-TSL-PCM-126"=>{"hosts"=>{"TSF-W01"=>{"ip"=>"192.168.0.201"}}}}}

您的变量/哈希中有错字,或者您正在尝试分配 的返回值puts,即 nil。


推荐阅读