Ruby: 循环调用关联数组(TypeError 没有将 String 隐式转换为 Integer)

Ruby: Looping and calling associative arrays (TypeError no implicit conversion of String into Integer)

所以我有这段代码:

node['nginx'][0]['server_name']='black.domain.com'
node['nginx'][0]['app_server']='http://10.50.0.163:8090'
node['nginx'][0]['redirect_path']='/mesh'

node['nginx'][1]['server_name']='red.domain.com'
node['nginx'][1]['app_server']='http://10.50.0.163:8090'
node['nginx'][1]['redirect_path']='/mesh'

node.default['nginx'].each do |key, value|
    value.each do |prop|
            Chef::Log.info prop['app_server']       
    end
end

如标​​题所示,错误出自:

 21>>       Chef::Log.info prop['app_server']

我的问题是如何遍历这个关联数组?

最好的, -尤利安

您的循环应如下所示:

node.default['nginx'].each do |node_properties|
  Chef::Log.info node_properties['app_server']
end

您可以像这样遍历 node['nginx']。 (我不知道 node.default['nginx'] 应该是什么)

node['nginx'].each do |num, hash|
  #on the first iteration: 
  #  num = 0
  #  hash = {'server_name' => 'black.domain.com', 'app_server' => 'http://10.50.0.163:8090', 'redirect_path' => '/mesh'}
  #on the second iteration
  #  num = 1
  #  hash = {'server_name' => 'red.domain.com', 'app_server' => 'http://10.50.0.163:8090', 'redirect_path' => '/mesh'}
  #now you can do what you want with the data eg
  Chef::Log.info hash['app_server'] 
end

虽然代码非常好,但让我建议您另一种构造属性的方法:使用散列而不是数组:

node['nginx']['black_1']['server_name'] = 'black1.domain.com'
node['nginx']['black_1']['app_server'] = 'http://10.50.0.163:8090'
node['nginx']['black_1']['redirect_path'] = '/mesh'

node['nginx']['black_2']['server_name'] = 'black2.domain.com'
node['nginx']['black_2']['app_server'] = 'http://10.50.0.163:8090'
node['nginx']['black_2']['redirect_path'] = '/mesh'

您可以使用以下方式遍历它:

node['nginx'].each do |site_name, node_properties|
  Chef::Log.info node_properties['app_server']
end

原因:

很难 delete/manipulate 排列 chef 属性中的元素,例如使用节点属性或在包装器食谱中。假设您需要更改某个站点的 IP 地址或端口,例如在包装器说明书中为某些 "stage"/"testing" 环境部署设置。您需要知道记录在数组中的位置,否则您将不得不循环到整个数组并进行查找,例如server_name 以匹配正确的条目。

详情:

  1. "Prefer Hashes of Attributes to Arrays of Attributes"
  2. "Arrays and Chef"