# Looping through an array

**URL:** <https://discourse.chef.io/t/looping-through-an-array/10085>\
**Category:** Chef Infra (archive)\
**Created:** [December 19, 2016, 3:19pm UTC](https://discourse.chef.io/t/looping-through-an-array/10085 "2016-12-19T15:19:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![AngryInca](https://avatars.discourse-cdn.com/v4/letter/a/2acd7d/32.png) [@AngryInca](https://discourse.chef.io/u/AngryInca)\
**Post date:** [December 19, 2016, 3:19pm UTC](https://discourse.chef.io/t/looping-through-an-array/10085/1 "2016-12-19T15:19:29Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![drpebcak](https://avatars.discourse-cdn.com/v4/letter/d/6f9a4e/32.png) [@drpebcak](https://discourse.chef.io/u/drpebcak)\
**Post date:** [December 19, 2016, 3:36pm UTC](https://discourse.chef.io/t/looping-through-an-array/10085/2 "2016-12-19T15:36:24Z")

</div>

```auto
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,

```auto
%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.
