ruby - 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 :(
解决方案
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。
推荐阅读
- python - 通过单词后面的第二个元音从字符串中获取子字符串
- javascript - 任何 php 请求都返回 502 Bad Gateway
- c++ - 如何在 C++ 中声明抽象类的向量列表?
- arrays - 反应数组的显示对象
- c - 每次调用多次的函数的堆栈帧是否不同?
- ios - 我将如何获得此功能以停止重复问题?
- java - Elasticsearch 排除包含特定术语的文档
- android - 滚动另一个recyclerview时实现recyclerview持有者视图大小更改
- java - 将 JTable 添加到 JFreeChart ChartPanel
- php - 会话和会话变量不起作用