-1

I got the following template:

|Info1|Info2|Info3|Info4|Info5|Info6|Info7|Info8|Info9|Info10|
|Info11|Info12|Info13|Info14|Info15|Info16|Info17|Info18|Info19|Info20|

And I have to substitute each information with real data and put it into a .txt file, what could be a good way to handle this in Ruby?

Thx

Eric Martins
  • 460
  • 4
  • 17

1 Answers1

2

Place this in a file called subtemplate.rb:

subs = { 'Info1' => "Hello", 'Info2' => 'World' }

STDIN.each do |line|
    puts line.gsub(/\w+/) { |m| subs[m] }
end

Run from the command line:

 ruby subtemplate.rb < template.txt > output.txt

where template.txt contains the template file. Then output.txt is

|Hello|World|||||||||
|||||||||||
Matt
  • 20,108
  • 1
  • 57
  • 70
  • +1 but might want to use `/\b\w+\b/` so `Info1` doesn't clobber `Info10`. – maerics Mar 06 '14 at 19:05
  • @maerics `\w+` is a "greedy" match; it will consume all available `\w` characters. As you can see from this example, it did not match `Info10`. – Matt Mar 06 '14 at 19:07
  • I know It's a bad way to handle templates, but It's the way a federal institution here in Brazil requires me to send them information via its webservice :facepalm: – Eric Martins Mar 06 '14 at 19:17