Looping through an array


#1

Hi,

I would like to run this code:

cookbook_file "#{utilities_directory}\\fileXYZ.xml" do
  source "#{files_directory}/fileXYZ.xml"
end

For 15 files, fileX.xml, fileY.xml, fileZ.xml etc. etc. Rather than copy and pasting it 15 times into a recipe I was hoping i could store all my files into an array and then loop through the array so I only have the above code block once.

I can’t quite get it to work, what I have so far is:

file_array = ['fileX.xml', 'fileY.xml', 'fileZ.xml']

cookbook_file "#{utilities_directory}\\" + file_array.each do |this_file|
  source "#{files_directory}/this_file"
end

Can anyone point out how I need to change this or point me to a resource that has an example?

Thanks!


#2
file_array = ['fileX.xml', 'fileY.xml', 'fileZ.xml']
file_array.each do |this_file|
  cookbook_file "#{utilities_directory}\\" + this_file do
    source "#{files_directory}/#{this_file}"
  end
end

Or,

%w(fileX.xml fileY.xml fileZ.xml).each do |this_file|
  cookbook_file "#{utilities_directory}\\" + this_file do
    source "#{files_directory}/#{this_file}"
  end
end

Note: I didn’t test this, but that’s the general idea of looping. You want to loop via ‘regular ruby’ as opposed to with the Chef DSL.