Navarro Navarro - 1 month ago 5
Ruby Question

Looping through ruby hashes

I am trying to follow this example, however when I can't find a way to loop through the hash as he does:

...
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
...


I get the following error:

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


For some reason the
|a, (b,c)|
is not working, the round brackets are ignored.

Seems like
platform
contains (as expected) 'MyOS', however the iterator
package
equals '{"package"=>"package", "versions"=>["1.0", "2.0", "3.0"]}' and
versions
is empty.

I am expecting the following:

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


So I am able to access the package name while looping through the versions of the platform.

Answer

Try this. Every platform has a name and a set of attributes. Every attribute has a name and a value.

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