循环通过红宝石哈希

时间:2016-10-25 12:14:10

标签: ruby

我正在尝试关注this example,但是当我找不到像他一样循环哈希的方法时:

...  
platforms = {
  'MyOS' => {
    'package' => 'package',
    'versions' => ['1.0', '2.0','3.0']
  }
}
...
platforms.each do |platform, (package, versions)|
  versions.each do |version|
    context "On #{platform} #{version}" do
    before do
      Fauxhai.mock(platform: platform, version: version)
    end

    let(:chef_run) { ChefSpec::ChefRunner.new.converge('cookbook::recipe') }

    it "Installs the package" do
      chef_run.should install_package package
    end
  end
end
...

我收到以下错误:

/path/file.rb:XX:in `block (2 levels) in <top (required)>': undefined method `each' for nil:NilClass (NoMethodError)

由于某些原因,|a, (b,c)|无效,圆括号将被忽略。

似乎platform包含(按预期)'MyOS',但迭代器package等于'{“package”=&gt;“package”, “versions”=&gt; [“1.0”,“2.0”,“3.0”]}'versions为空。

我期待以下内容:

platform = "MyOS"
package = "package"
versions = ["1.0", "2.0", "3.0"]

因此,我可以在循环浏览平台版本时访问软件包名称。

2 个答案:

答案 0 :(得分:2)

试试这个。每个平台都有一个名称和一组属性。每个属性都有一个名称和一个值。

platforms.each do |name, platform|
  puts "platform = #{name}"
  platform.each do |attribute, value|
    puts "#{attribute} = #{value}"
  end
end

答案 1 :(得分:1)

如果我们有

platforms = { 'MyOS' => { 'package'=>'package', 'versions' => ['1.0', '2.0','3.0'] } }

platforms.each do |platform, (package, versions)|...

传递给块的platforms的第一个(也是唯一的)元素(键值对)是

platforms.first
  #=> ["MyOS", {"package"=>"package", "versions"=>["1.0", "2.0", "3.0"]}]

您正在将块变量分配给此值:

platform, (package, versions) = ["MyOS", {"package"=>"package",
  "versions"=>["1.0", "2.0", "3.0"]}]

通过并行分配(有时称为多重赋值),Ruby获得:

platform          #=> "MyOS" 
package, version  #=> {"package"=>"package", "versions"=>["1.0", "2.0", "3.0"]}

然后再次申请平行作业,她获得:

package           #=> {"package"=>"package", "versions"=>["1.0", "2.0", "3.0"]}
versions          #=> nil 

这不是你想要的。考虑到platform.first只包含两个元素,这个结果也不应该令人惊讶。相反,您需要两个块变量platform, h,以便

platform, h = ["MyOS", {"package"=>"package", "versions"=>["1.0", "2.0", "3.0"]}]
platform #=> "MyOS" 
h #=> {"package"=>"package", "versions"=>["1.0", "2.0", "3.0"]}

然后在块中你需要操纵哈希h