Dan
Dan

Reputation: 1033

ruby and nested loops

Hi I'd like some help on how to code this in erb in puppet, basically I have

server::actionhost { 'details':
    servername[ 'felix', 'washington', ],
    ipa [ '192.168.43.5', '192.168.43.11', ],
    enviro [ 'prod', 'uat', ],
}

I now want to print this out to a file with each respective element from each array in one line, i.e the output from the template file in my class should be like:

felix 192.168.43.5 prod
washington 192.168.43.11 uat

When I attempted this I wrote the following code in my template file:

<% servername.each do |name| -%>
<% ipa.each do |ip| -%>
<% enviro.each do |env| -%>
<%= name %> <%= ip %> <%= env %>
<% end -%>
<% end -%>
<% end -%>

but what I get is recursive prints of netmask and ipa instead of a print from each array and then move to the next array element.

Would appreciate some guidance on how to accomplish the correct output?

Thanks Dan

Upvotes: 2

Views: 2079

Answers (3)

chandank
chandank

Reputation: 1001

How about trying something like dictionary. A similar approach worked for me hope it is helpful to you. My problem was, I had different variables and each should have a different value or parameters.

Define the variable like

 $file_threshold = {
          'received' => '10',
          'doneJobs' => '20',
          'recvq'    => '30',
          'sendq'    => '40',
          'doneq'    => '50',
          'docq'     => '60',}

In the template file

<%  @file_threshold.each do |key,value| -%>

cmd = check_file.sh <%=  key %>  <%= value%>

<% end -%>

Out:

....
cmd = check_file.sh doneq 50
....

Upvotes: 2

kclair
kclair

Reputation: 2224

This is kind of dicey because it assumes that you are absolutely sure that your arrays line up, but:

...<% servername.each_with_index do |name, i| -%>
.....<%= name %> <%= ipa[i] %> <%= enviro[i] %>
...<% end %>

(please ignore the ... i couldn't get the template code to appear correctly otherwise!)

Upvotes: 0

Albert Turri
Albert Turri

Reputation: 361

One can execute Ruby code (the following is Ruby code) inside an .erb, if need be. The main things in this case are: defining a multi-dimensional array and using Ruby's transpose method for arrays.

<% details = [servername, ipa, env]; transposed = details.transpose; transposed.each {|x| print x.at(0), " ", x.at(1), " ", x.at(2), "\n"}  %>

Upvotes: 1

Related Questions