1

I have an erb file with a lot of these and I am trying to create a loop for them:

<% if @addhostgroup -%>
  <% @addhostgroup.each do |k, v| %>
    <%= k %> <%= v %>
  <% end %>
<% end %>

<% if @addservicegroup -%>
  <% @addservicegroup.each do |k, v| %>
    <%= k %> <%= v %>
  <% end %>
<% end %>

What I want to do is something like this:

<% %w(addhostgroup addservicegroup).each do |action| %>
  <% if @action -%>
    <% @action.each do |k, v| %>
      <%= k %> <%= v %>
    <% end %>
  <% end %>
<% end %>

Can somebody tell me how to use variables on erb variables names?

I was searching for a way without success.

Thank you very much!

2
  • Please show your recipe code also, we can't guess what you give to the template resource with only this few lines Commented Dec 13, 2018 at 10:23
  • 1
    It's usually a good idea to keep templates simple / dumb / logic-less. Have you considered merging the hashes outside the template and just passing a single hash? Commented Dec 13, 2018 at 10:39

2 Answers 2

4

Edit: An easier way would be to make a normal array instead of a percent literal. [@addhostgroup, @addservicegroup].each do |action|. Sometimes I over look the little things :)

You can use instance_variable_get along with the array and iteration into action that you have setup.

Add a line immediately inside the each block with: <% instance_var_value = instance_variable_get(:"@#{action}") %>

You could also map the values into the array before iterating over it.

Sign up to request clarification or add additional context in comments.

Comments

2

The problem is that block variable action holds a string with the name of the action. You want to call @variable with dynamic name based on the name. You are searching for this piece of code:

instance_variable_get("@#{action}")

4 Comments

The block variable action will have precedence over the method action within the block, so that would not be a problem.
You're right, my wording fault... I'll edit my answer.
@DonPaulie, thank you for your help. This is what I've looked for. I will accept Tom's answer because he just replied first.
@ice I was glad to help. I know, I only did not want to delete it just because another answer appeared before I completed mine :-D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.