Is this the best way to use a regex and build a file?

Hello,

I only have shallow knowledge of Ruby, and would like to check this is the best way to create a text file by reading items from another file through a regex:

header = "<?xml version=""1.0"" encoding=""UTF-8""?>\n<gpx>\n<trk>\n<name>RENAME ME</name>\n<trkseg>\n"
footer = "</trkseg>\n</trk>\n</gpx>\n"

File.open('test.gpx', 'w') do |file|
	file.puts header

	meat = File.read('input.gpx')
	meat.scan(/<trkpt.+?<\/trkpt>/m) { |mtch| 
	  file.puts mtch
	}
	
	file.puts footer
end

Thank you.

meat will be the contents of the entire file. If input.gpx is small, then it will be fine. Otherwise, you will want to process either by lines or by blocks.

But looks like the file is an XML file.

You should process it with an XML parser instead.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs