Skip to content

Instantly share code, notes, and snippets.

@moxley
Created April 16, 2013 17:35
Show Gist options
  • Save moxley/5397878 to your computer and use it in GitHub Desktop.
Save moxley/5397878 to your computer and use it in GitHub Desktop.
Prototype string replacer that parses the input character-by-character. Final implementation to be written in Go.
# To test, create a text file called test.txt in the current directory with the following content:
#
# Hello foo...
#
# Then run: ruby file_string_replacer.rb
# It will output send the modified version of the file contents to STDOUT
class FileStringReplacer
attr_accessor :file_path, :char
def initialize(file_path)
self.file_path = file_path
@chunk_index = 0
@match_index = nil
end
def file
@file ||= File.open(file_path, 'r')
end
def next_chunk
if file.eof?
@eof = true
return nil
end
@chunk_index = 0
@chunk = file.read(4)
@eof = true if file.eof?
@chunk
end
def eof?
@eof ? true : false
end
def next_char
if @chunk.nil? || @chunk_index >= @chunk.length
@chunk = next_chunk
end
return nil if @chunk.nil?
@char = @chunk[@chunk_index]
@chunk_index += 1
@char
end
def replace(pattern, replacement)
while ch = next_char
quit unless ch
if ch == pattern[0]
parse_match(pattern, replacement)
else
send(ch)
end
end
quit
end
def send(str)
print str
end
def quit
file.close
end
def parse_match(pattern, replacement)
match_buf = ''
@match_index = 0
while char && pattern[@match_index] && char == pattern[@match_index]
match_buf += char
@match_index += 1
next_char
end
if match_buf.length == pattern.length
# we found a match
send(replacement)
end
send(char) if char
end
end
r = FileStringReplacer.new('test.txt')
r.replace('foo', '0')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment