【问题标题】:Ruby: Looping and calling associative arrays (TypeError no implicit conversion of String into Integer)Ruby:循环和调用关联数组(TypeError 没有将字符串隐式转换为整数)
【发布时间】:2015-06-12 22:12:15
【问题描述】:

所以我有这段代码:

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']的值是多少?
  • 它没有被分配任何东西

标签: ruby-on-rails arrays ruby chef-infra


【解决方案1】:

您可以像这样遍历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

【讨论】:

  • 谢谢。那么..我如何输出这些值?
  • 不过,你应该知道,如果 hash = {'server_name' => 'red.domain.com', 'app_server' => 'http://10.50.0.163:8090', 'redirect_path' => '/mesh'} 并且你想要 'app_server' 值,你会说 hash['app_server'] - 这只是基本的哈希访问。
  • 太好了,您可以推荐关于这个主题的任何特定的 ruby​​ 页面吗?谢谢你,-尤利安
  • 这是一个基本的语言功能,如果您不知道,我建议您从头开始。 codecademy.com/en/tracks/ruby
【解决方案2】:

你的循环应该是这样的:

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

【讨论】:

  • 谢谢 Yury,但我得到了同样的结果
【解决方案3】:

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

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

原因:

在厨师属性中删除/操作数组元素非常困难,例如使用节点属性或在包装说明书中。假设您需要更改某个站点的 IP 地址或端口,例如在包装说明书中为某些“阶段”/“测试”环境部署设置。您需要知道记录在数组中的位置,否则您必须循环到整个数组并查找例如server_name 以匹配正确的条目。

详情:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多