From: MonkeeSage Date: 2007-12-05T00:10:15+09:00 Subject: Re: changing a files' content On Dec 4, 3:18 am, Paul Fox wrote: > hi all, > i have a text file with various lines, and i want to alter some of these > using regex and gsub. > > so i have patterns={/some_pattern/=>"replacement text"} > and i'm thinking this: > in = File.open(filename) > while (line=in.gets) > if line.strip =~ pattern > line.gsub(pattern,patterns[pattern]) > end > end > > but i'm not sure if that's efficient? and of course, i'm struggling on > the best way of writing those changes back into the file. > > any thoughts? > thanks, > f. > -- > Posted viahttp://www.ruby-forum.com/. patterns = { /some_pattern/ => "replacement text" } File.open(filename, 'r+') { | handle | out = [] handle.readlines { | line | patterns.each { | pattern, replacement | if line.strip =~ pattern line = line.gsub(pattern, replacement) end } out << line } handle.write(out.join('')) } Untested... Regards, Jordan