kfmfe04
kfmfe04

Reputation: 15337

How do I search-and-replace strings (not regex) in Ruby?

I have used gsub previously for a regex match, but what should I call for string literals?

I want to replace pair[0] with pair[1] wherever pair[0] is found in the file.

text = File.read( fname )  
@hash_old_to_new.each do
  |pair|
  puts "\tReplacing " + pair[0] + " with " + pair[1]
  # result = text.gsub( /pair[0]/, pair[1] )  <--- this is no good
end
File.open( fname, "w" ) { |file| file << result }

Upvotes: 2

Views: 1709

Answers (2)

SwiftMango
SwiftMango

Reputation: 15304

You were not far from the answer:

Directly use string in gsub:

result = text.gsub( pair[0], pair[1] )

Or use a string in regex:

result = text.gsub( /#{pair[0]}/, pair[1] )

Upvotes: 1

Alex D
Alex D

Reputation: 30485

gsub also works for string literals.

text.gsub!(pair[0], pair[1])

Note that gsub returns a new String, rather than modifying the existing String "in place". Because of the way your code is written, this will cause you to lose updates. You can use gsub!, or else you can chain calls like this:

text = text.gsub(pair[0], pair[1])

Upvotes: 6

Related Questions