# Writing erb rhtml output to an external file

**URL:** <https://www.ruby-forum.com/t/writing-erb-rhtml-output-to-an-external-file/157393>\
**Category:** Ruby\
**Created:** [January 10, 2009, 3:02pm UTC](https://www.ruby-forum.com/t/writing-erb-rhtml-output-to-an-external-file/157393 "2009-01-10T15:02:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![glenn](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/4bbf92/32.png) [@glenn](https://www.ruby-forum.com/u/glenn)\
**Post date:** [January 10, 2009, 3:02pm UTC](https://www.ruby-forum.com/t/writing-erb-rhtml-output-to-an-external-file/157393/1 "2009-01-10T15:02:27Z")

</div>

Hi,

I am trying to write the output of an erb run to an external output  
file. I have an object with some instance variables in it, and a string  
of html and the instance variables (in the erb style with \<% and \<%=).

I require erb and create a local variable that’s a erb object, then call  
run on that object, like this:

require “erb”

template = %q{  
some html in here

}.gsub(/^ /, ‘’)

f = File.new(‘myfile.rhtml’, ‘w’)  
rhtml = ERB.new(template)  
rhtml.run(o.get\_binding)

I just can’t figure out how to direct the result into the f file object.  
Any suggestions?

I read a lot of the documentation but did not see (or understand) a  
reference to this.

Thanks!

---

<div class="post-metadata">

**Author:** ![glenn](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/4bbf92/32.png) [@glenn](https://www.ruby-forum.com/u/glenn)\
**Post date:** [January 10, 2009, 4:15pm UTC](https://www.ruby-forum.com/t/writing-erb-rhtml-output-to-an-external-file/157393/2 "2009-01-10T16:15:44Z")

</div>

Le 10 janvier 2009 à 15:01, Glenn a écrit :

> f = File.new(‘myfile.rhtml’, ‘w’)  
> rhtml = ERB.new(template)  
> rhtml.run(o.get\_binding)
> 
> I just can’t figure out how to direct the result into the f  
> file object. Any suggestions?

You have a ‘result’ method :

File.open('myfile.rhtml, ‘w’) do |f|  
f.puts ERB.new(template).result(o.get\_binding)  
end

Note too that the block form of File is usually preferred, if only  
because the handles are automatically closed at the end of the block  
without the need of a call to close.

Fred
