关于ruby:Puppet:嵌套的hash / dict,array:如何在erb中访问?

Puppet: nested hash/dict,array: how to access in erb?

玩木偶,我最终陷入了一个嵌套的字典/哈希-看起来或多或少像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$settings =
{
 "var1" =>
  {
   "ip" =>"0.0.0.0",
   "port" =>"1234",
   "option" => ["foo","bar"],
   "machines" =>
    {
     "maschine-1" => {"ip" =>"1.2.3.4","port" =>"1234"},
     "maschine-2" => {"ip" =>"1.2.3.5","port" =>"1235"},
    }  
  }
}

但是,我没有设法在对应的erb模板中正确解析它。

1
2
3
4
5
6
7
8
<% @settings.each_pair do |settings_key, settings_value_hash| %>
<%= settings_value_hash['ip']%>:<%= settings_value_hash['port'] %>

option <% @settings_value_hash['option'].each do |option| -%> <%= option  %>   <% end -%>

<% @{settings_value_hash['machines']}.each_pair do |machine_key, machine_value_hash| %>
  server <%= machine_key %>  <%= machine_value_hash['ip'] %>:<%= machine_value_hash['port'] %>
<% end %>

因此,我可以毫无问题地在顶级字典中获取值,即" ip"和" port",

但是,当我尝试访问顶部dict中的数组" option"或dict" machines"时,p会抛出编译错误。

我目前的猜测是,在Ruby / Puppet中数组和dict /散列不是"可哈希的",或者?

干杯,感谢您的想法,
托马斯


不确定您在做什么,但未定义一些明显的问题,例如@settings_value_hash,它将是settings_value_hash管道变量而不是实例变量。 @{settings_value_hash['machines']}也是正确的,如果运行此

会发生什么

1
2
3
4
5
6
7
8
9
10
<% @settings.each do |settings_key, settings_value_hash| %>
  <%="#{settings_value_hash['ip']}:#{settings_value_hash['port']}" %>
  option
  <% settings_value_hash['option'].each do |option| %>
    <%= option  %>  
  <% end %>
  <% settings_value_hash['machines'].each do |machine_key, machine_value_hash| %>
    server <%="#{machine_key} #{machine_value_hash['ip']}:#{machine_value_hash['port']}" %>
  <% end %>
<% end %>

也为什么将初始哈希设置为全局$settings,但是您正在通过实例变量@settings访问它。