Gavin Kistner
10/27/2004 12:40:00 PM
On Oct 26, 2004, at 10:06 PM, Bill Atkins wrote:
> I think what he's saying is that <%= "34" %> will output a 34 to the
> result, but <% puts 34 %> will output that stream to STDOUT. So if he
> were calling ERb#result, he'd get the result of the former in its
> return value but the second statement's output wouldn't go into the
> result string.
Ah, you're right. I was confused because of the limited test case I was
doing.
These two tests make clear that what you say is true:
Test 1:
require 'erb'
a = 99
puts ERB.new( "<% print a %> bottles of beer. <% print a %> I say."
).result( binding )
#=> 9999 bottles of beer. I say.
Test 2:
require 'erb'
a = 99
ERB.new( "<% print a %> bottles of beer. <% print a %> I say."
).result( binding )
#=> 9999
Now I understand James' question. The above is NOT what I would have
expected, and at odds with the Pickaxe quote. It means that the
following code does not work like the equivalent would in something
like ASP:
require 'erb'
erb = ERB.new <<ENDERB
<h1>Hello, World</h1>
<p>I like cheese because:</p>
<ol>
<%
reasons = [ "It's bad for me", "It is tasty", "And so yes" ]
reasons.each{ |reason|
puts "\t<li>#{reason}</li>"
}
%>
</ol>
Done.
ENDERB
puts erb.result( binding )
Er...in fact, the above doesn't run at all, oddly.
tmp.rb:12: undefined local variable or method `reason' for main:Object
(NameError)
Changing the block to:
<%
3.times{ puts "<li>Just because.</li>" }
%>
produces the final output:
#=> <li>Just because.</li>
#=> <li>Just because.</li>
#=> <li>Just because.</li>
#=> <h1>Hello, World</h1>
#=>
#=> <p>I like cheese because:</p>
#=> <ol>
#=>
#=> </ol>
#=> Done.
...which is clearly not what is desired. Perhaps there's some way to
run IRB that hijacks STDOUT that I don't know about.
Finally, to be clear, the following DOES work:
require 'erb'
erb = ERB.new <<ENDERB
<h1>Hello, World</h1>
<p>I like cheese because:</p>
<ol>
<%
reasons = [ "It's bad for me", "It is tasty", "And so yes" ]
reasons.each{ |reason|
%>
<li><%=reason%></li><%
}
%>
</ol>
Done.
ENDERB
puts erb.result( binding )
outputting:
#=> <h1>Hello, World</h1>
#=>
#=> <p>I like cheese because:</p>
#=> <ol>
#=>
#=> <li>It's bad for me</li>
#=> <li>It is tasty</li>
#=> <li>And so yes</li>
#=> </ol>
#=> Done.