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!!!
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 w
rite 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With