views:

112

answers:

1

I expected to see the word "test" appear in the output once and the word "hello" appear once.

But I'm puzzling over the fact that if I do this, the word "test" is displayed twice.

<div>
  <h3>test</h3>
</div>

<% def helo %>
 <% "hello" %>
<% end %>

<%= helo %>

I assume there's a simple explanation for this related to some quirk of erb?

+1  A: 

I tried it:

require 'erb'

template = %q{
    <div>
      <h3>test</h3>
    </div>

    <% def helo %>
      <% "hello" %>
    <% end %>

    <%= helo %>
}

t = ERB.new(template)
puts t.result

#(erb):6:in `helo': undefined local variable or method `_erbout' for main:Object (NameError) from (erb):10

So it seems what you are mentioning is right, but on all hows, you can trick it easily:

require 'erb'

template = %q{
    <div>
      <h3>test</h3>
    </div>

    <% def helo
      "hello"
    end %>

    <%= helo %>
}

message = ERB.new(template)
puts message.result

And it worked for me.

khelll