problems iterating in RUBY while extracting info from YAML, Pls help!

Hi all,
I am stuck with a ruby script that extracts detials from yaml file and processes accordingly.
the yaml file

confivnic:
  device:
    vnic1:
      policy:
      - L2
      mode: active
    vnic2:
      policy:
      - L3
      - L4
      mode: active
  type: aggr

notsoconfi:
  device:
    vnic9:
      policy:
      - L2
      - L3
      mode: "off"
    vnic3:
      policy:
      - L2
      - L3
      mode: active
    vnic6:
      policy:
      - L3
      - L2
      mode: active
  type: aggr

the ruby script

require 'yaml'
yaml = YAML::load(File.open("testyaml.yaml"))

yaml.each do |name, option|
if option['type'] == "aggr"
names = Array.new
names.push name
while names.size != 0
key = yaml.keys.first
tpl = "dladm create-{{{type}}} {{{sets}}} {{{cmd}}}"
tpl.gsub! '{{{type}}}', yaml[key]['type']
tpl.gsub! '{{{cmd}}}',  key
sets = ''
set_tpl = '-l {{{key}}} -L={{{mode}}} -P={{{policy}}} '
yaml[key]['device'].each do |device|
  set = set_tpl.dup
  set.gsub! '{{{key}}}',    device[0]
  set.gsub! '{{{mode}}}',   device[1]['mode']
  set.gsub! '{{{policy}}}', device[1]['policy'].join(',')
  sets << set
end
names.pop
end
tpl.gsub! '{{{sets}}}', sets
puts tpl.gsub(/\s+/,' ')
end
end

The o/p i get is like this

dladm create-aggr -l vnic9 -L=off -P=L2,L3 -l vnic3 -L=active -P=L2,L3 -l vnic6 -L=active -P=L3,L2 notsoconfi
dladm create-aggr -l vnic9 -L=off -P=L2,L3 -l vnic3 -L=active -P=L2,L3 -l vnic6 -L=active -P=L3,L2 notsoconfi

but the yaml file has 2 names ,"confivnic" and "notsoconfi"
This was written originally for just one module but for obvious reasons we had to change it. I tried all i knew but really not finding a way out.
The things that i feel are creating errors are yaml.keys.first
or the way iteration is done.

The o/p i want is similar to the shown one but instead of repeating the same one twice i want the other one to be displayed as well with the necessary changes.

Pls help

Yes, one of your problems is the repeated calls to yaml.keys.first. (will always return 'notsoconfi')

The following code delivers the expected output:

require 'yaml'

set_tpl = '-l {device} -L={mode} -P={policy} '

yaml = YAML::load(File.open("testyaml.yaml"))

yaml.each do |name, option|
   if option['type'] == "aggr"
      tpl = 'dladm create-{type} {sets} {cmd}'
      tpl.gsub! '{type}', option['type']
      tpl.gsub! '{cmd}', name

      sets = ""
      yaml[name]['device'].each do |device|
         set = set_tpl.dup
         set.gsub! '{device}', device[0]
         set.gsub! '{mode}',   device[1]['mode']
         set.gsub! '{policy}', device[1]['policy'].join(',')
         sets << set
      end

      tpl.gsub! '{sets}', sets
      puts tpl.gsub(/\s+/,' ')
   end
end
dladm create-aggr -l vnic9 -L=off -P=L2,L3 -l vnic3 -L=active -P=L2,L3 -l vnic6 -L=active -P=L3,L2 notsoconfi
dladm create-aggr -l vnic1 -L=active -P=L2 -l vnic2 -L=active -P=L3,L4 confivnic