tags:

views:

55

answers:

4

I'm new to ruby and was hoping someone could help me figure out how to open a file, then using gsub to find and replace by multiple conditions.

Here's what I got so far but this doesn't seem to work as the 2nd replace var overrides the first:

text = File.read(filepath)
replace = text.gsub(/aaa/, "Replaced aaa with 111")
replace = text.gsub(/bbb/, "Replace bbb with 222")
File.open(filepath, "w") {|file| file.puts replace}
+5  A: 

You're replacing from the original "text" each time, the second line needs to replace the replace:

replace = replace.gsub(/bbb/, "Replace bbb with 222")
Adam Vandenberg
Thanks this worked.
A: 

Change the third line to

replace = replace.gsub(/bbb/, "Replace bbb with 222")
dasil003
Thanks this worked.
+3  A: 

An interesting wrinkle to this is if you don't want to rescan the data, use the block form of gsub:

replace = text.gsub(/(aaa|bbb)/) do |match|
  case match
    when 'aaa': 'Replaced aaa with 111'
    when 'bbb': 'Replace bbb with 222'
  end
end

This may not be the most efficient way to do things, but it's a different way to look at the problem. Worth benchmarking both ways if performance matters to you.

Steve Ross
Nice, I imagine that also prevents compiling the pattern twice.
DigitalRoss
A: 

I might be tempted to write it like this...

#!/usr/bin/env ruby

filepath = '/tmp/test.txt'

File.open filepath, 'w' do |f|
  $<.each_line do |line|
    f.puts line.gsub(/aaa/,
      'Replaced aaa with 111').gsub /bbb/, 'Replace bbb with 222'
  end
end
DigitalRoss