Skip to content

Instantly share code, notes, and snippets.

@Narnach
Last active February 3, 2016 11:37
Show Gist options
  • Save Narnach/a336631a153c8c8a2406 to your computer and use it in GitHub Desktop.
Save Narnach/a336631a153c8c8a2406 to your computer and use it in GitHub Desktop.
# The regexp is re-compiled for every line in the file, which is SLOW
# If you are processing a lot of data, inline regexps are to be avoided!
class SlowWorker
def initialize(custom)
@custom = custom
end
def call(file)
File.open(file,'r') do |file|
file.each_line do |line|
puts if line =~ /my arbitrary #{@custom} regexp/
end
end
end
end
# The regexp is compiled once, which is FAST.
# The regexp is always the same, so a constant makes sense for storing it.
class FastWorker
REGEXP = /my arbitrary regexp/
def call(file)
File.open(file,'r') do |file|
file.each_line do |line|
puts if line.match(REGEXP)
end
end
end
end
# If your regexp depends on some custom values, create it once when initializing the class.
class CustomFastWorker
def initialize(value)
@regexp = /my arbitrary #{value}/
end
def call(file)
File.open(file,'r') do |file|
file.each_line do |line|
puts if line.match(@regexp)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment