1

I have the following code in an ERB template:

<% ['foo', 'bar'].each do |var| %>
  <%= previous %>
  <% previous = "#{var}" %>
<% end %>

I would expect it to output foo, but it outputs nothing, previous is always nil. previous is not defined outside the loop, the first assignment happens after the end of the first loop.

This is how I'm rendering the template:

f.write ERB.new(File.read(node)).result(namespace.instance_eval { binding })

What am I doing wrong?

1 Answer 1

1

try this

<% previous = "" %>
<% ['foo', 'bar'].each do |var| %>
  <%= previous %>
  <% previous = var %>
<% end %>
Sign up to request clarification or add additional context in comments.

1 Comment

You had a scoping issue and the var thing you did was a syntax bug

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.