A more elegant way to do this?


#1

Can anybody suggest a more elegant and rubyish way to do this?

I am reading a YAML file and then trying to iterate over arrays and
hashes that may or may not be there.

unless conf[‘hosts’][hostname][‘groups’].nil?
conf[‘hosts’][hostname][‘groups’].each { |group|
unless conf[‘crontables’][group].nil?
conf[‘crontables’][group].each { | tab_item|
tab_entries << tab_item
}
end #Unless
}
end #unless


#2

On Thu, 11 May 2006, Tim U. wrote:

   }
end #Unless

}
end #unless

array = lambda{|x| x || []}

array[conf[‘hosts’][hostname][‘groups’]].each {|group|
array[conf[‘crontables’][group]].each {|tab_item|
tab_entries << tab_item
}
}

hth.

-a


#3

Tim U. wrote:

    }
 end #Unless

}
end #unless

A slight variation on the other suggestions:

def each_element_of(enum)
enum and enum.each {|elt| yield elt}
end

each_element_of conf[‘hosts’][hostname][‘groups’] do |group|
each_element_of conf[‘crontables’][group] do |tab_item|
tab_entries << tab_item
end
end

Another slight variation:

conf[‘hosts’][hostname][‘groups’].to_a.each do |group|
conf[‘crontables’][group].to_a.each do | tab_item|
tab_entries << tab_item
end
end


#4

Tim U. wrote:

    conf['crontables'][group].each { | tab_item|
      tab_entries << tab_item
    }

A small suggestion for the above if tab_entries is an array:

tab_entries.concat(conf[‘crontables’][group])


#5

On 5/11/06, Tim U. removed_email_address@domain.invalid wrote:

     }
  end #Unless
}

end #unless

nil.to_a # => []

conf[‘hosts’][hostname][‘groups’].to_a.each do |group|
conf[‘crontables’][group].to_a.each do |tab_item|
tab_entries << tab_item
end
end