Skip to content

Instantly share code, notes, and snippets.

@fxn
Created February 12, 2012 03:30
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 fxn/1806049 to your computer and use it in GitHub Desktop.
Save fxn/1806049 to your computer and use it in GitHub Desktop.
require 'active_support/inflector'
require 'benchmark'
# QUICK HACK
class RuleSet
def initialize
@rules = []
@regexp = nil
end
def prepend_rule(pattern, replacement)
@rules.unshift([pattern, replacement])
patterns = @rules.each_with_index.map {|rule, i| build_regexp(rule.first, i)}
@regexp = Regexp.union(*patterns)
end
def build_regexp(pattern, i)
pattern = Regexp.quote(pattern) if pattern.is_a?(String)
/(?<_#{i}>#{pattern})/
end
def apply(word)
word = word.to_s.dup
if md = @regexp.match(word)
name = md.names.detect {|n| md[n]}
index = name[/\d+/, 0].to_i
word.gsub!(@rules[index][0], @rules[index][1])
end
word
end
end
rs = RuleSet.new
ActiveSupport::Inflector::Inflections.instance.plurals.each do |pattern, replacement|
rs.prepend_rule(pattern, replacement)
end
words = File.readlines('/usr/share/dict/words').map(&:chomp)
Benchmark.bmbm do |x|
x.report('AS') { words.each {|word| ActiveSupport::Inflector.pluralize(word) }}
x.report('RS') { words.each {|word| rs.apply(word) }}
end
__END__
Rehearsal --------------------------------------
AS 78.620000 0.940000 79.560000 ( 82.188521)
RS 11.630000 0.100000 11.730000 ( 11.876435)
---------------------------- total: 91.290000sec
user system total real
AS 80.500000 0.890000 81.390000 ( 83.407733)
RS 11.520000 0.100000 11.620000 ( 11.855246)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment