Skip to content

Instantly share code, notes, and snippets.

@mrrooijen
Created December 16, 2009 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrrooijen/258093 to your computer and use it in GitHub Desktop.
Save mrrooijen/258093 to your computer and use it in GitHub Desktop.
class File
def self.gsub(path, regexp, &block)
content = File.read(path).gsub(regexp, &block)
File.open(path, 'wb') { |file| file.write(content) }
end
def self.sub(path, regexp, &block)
content = File.read(path).sub(regexp, &block)
File.open(path, 'wb') { |file| file.write(content) }
end
end
# Examples
# This will look for the regular expression pattern 'class Awesome' inside the file.rb.
# Then it will replace 'class Awesome' with 'class Awesome\n\tinclude Awesomeness
# This will only occur on the first pattern that matches 'class Awesome'
File.sub('/path/to/file.rb', /class Awesome/) do |match|
"#{match}\n\tinclude Awesomeness"
end
# This will look for the regular expression pattern 'class Awesome' inside the file.rb.
# Then it will replace 'class Awesome' with 'class Awesome\n\tinclude Awesomeness
# This will occur on any pattern that matches 'class Awesome'
File.gsub('/path/to/file.rb', /class Awesome/) do |match|
"#{match}\n\tinclude Awesomeness"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment