Skip to content

Instantly share code, notes, and snippets.

@hpjaj
Last active August 29, 2015 14:10
Show Gist options
  • Save hpjaj/01a71a19c8ca297e0fe8 to your computer and use it in GitHub Desktop.
Save hpjaj/01a71a19c8ca297e0fe8 to your computer and use it in GitHub Desktop.
Week 3 - 2e.v2 - Inserted Word
def find_and_replace(content, old_string, new_string)
@content_to_be_reset = content
if File.file?("#{content}")
@original_content = File.read("#{content}")
new_file_content = @original_content.gsub(old_string, new_string)
File.write("#{content}", new_file_content)
else
@original_content = content
new_file_content = @original_content.gsub(old_string, new_string)
# gsub is better for testing purposes
# use gsub! if you want the string to retain its newly replaced content
end
end
def reset_test_file
File.write("#{@content_to_be_reset}", @original_content)
end
# Calling the above method, passing in the sample file
find_and_replace('plain_text.txt','word', 'inserted word')
# Reset the test file back to its original state
reset_test_file
# Calling the above method, passing in a sample string instead of a file
blah = "The bird, the bird, the bird is the word."
find_and_replace(blah,'word', 'inserted word')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment