Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use erb to output file after binding

I got the following example:

require 'erb' 

names = []
names.push( { 'first' => "Jack", 'last' => "Herrington" } )
names.push( { 'first' => "LoriLi", 'last' => "Herrington" } )
names.push( { 'first' => "Megan", 'last' => "Herrington" } )

myname = "John Smith"

File.open( ARGV[0] ) { |fh|

erb = ERB.new( fh.read )
print erb.result( binding )

accompanied by

text.txt
<% name = "Jack" %>
Hello <%= name %>


<% names.each { |name| %>
Hello <%= name[ 'first' ] %> <%= name[ 'last' ] %>
<% } %>

hi, my name is <%= myname %>

}

it prints nicely to screen.

what is the simplest way to output to another file: "text2.txt" instead of to the screen?

I know this is really a piece of cake for most of you experienced ruby masters, but for me who just picked up a Beginning Ruby from Novice...it's challenging now...but I want to use the code for real life purpose...

thank you!!!

like image 562
john Avatar asked Jun 03 '10 20:06

john


1 Answers

Note that ERB isn't printing this - you are.

print erb.result( binding )

Let's change that. We'll open the file handle, in w mode to write, and write the ERB result to the file.

File.open('text2.txt', 'w') do |f|
  f.write erb.result(binding)
end

File.open('text2.txt', 'w') opens the file text2.txt in write mode, and passes that file object into the block. f.write outputs its argument to the file. In some cases you might need to call f.close to allow other processes on your computer to access the file, but since we used the block notation here instead, the file is closed automatically at the end of the block.

Code untested - let me know if you get an error. Good luck on your coding journey!

like image 156
Matchu Avatar answered Sep 28 '22 04:09

Matchu