2

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 }
0

2 Answers 2

6

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])
Sign up to request clarification or add additional context in comments.

Comments

1

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] )

2 Comments

No reason to use a literal regex. Not sure how this improves on the existing answer.
@DaveNewton I am just giving all possible solutions in case someone googled and come in here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.