From: steve ross Date: 2011-11-08T09:58:03+09:00 Subject: Re: "A" and "an" articles in front of words On Nov 6, 2011, at 1:50 PM, Ryan Davis wrote: > > On Nov 6, 2011, at 12:59 , steve ross wrote: > >> Sorry to be late to the party on this one, but a regex seems a bit of a big hammer. How about: >> >> def article_for(noun) >> article = %w(a e i o u).include?(noun[0..0]) ? 'an' : 'a' >> "#{article} #{noun}" >> end >> >> irb(main):022:0> article_for 'dog' >> => "a dog" >> irb(main):023:0> article_for 'animal' >> => "an animal" > > A regex is not that big of a hammer, and doing this is one method dispatch over two has direct performance benefits (if that matters): > Yeah, but a lot of the performance improvement is because regex is a first class language feature, and thus implemented in C (try match() versus =~ to measure method dispatch overhead). That said, eliminating a method dispatch might not make as much difference when you start fleshing out the functionality with things like exception lists (like the Rails inflector) to handle cases like "unicorn" versus "uncle". > require 'benchmark' > > # # of iterations = 1000000 > # user system total real > # null_time 0.120000 0.000000 0.120000 ( 0.118742) > # article_for 8.440000 0.000000 8.440000 ( 8.444280) > # articlize 6.100000 0.010000 6.110000 ( 6.107140) > # articlize2 5.940000 0.000000 5.940000 ( 5.942385) > > def article_for(noun) > article = %w(a e i o u).include?(noun[0..0]) ? 'an' : 'a' > "#{article} #{noun}" > end > > def articlize noun > article = /^[aeiou]/ =~ noun ? 'an' : 'a' > "#{article} #{noun}" > end > > # just to see if this makes much of a difference > def articlize2 noun > "#{/^[aeiou]/ =~ noun ? 'an' : 'a'} #{noun}" > end > > max = (ARGV.shift || 1_000_000).to_i > > puts "# of iterations = #{max}" > Benchmark::bm(20) do |x| > x.report("null_time") do > for i in 0..max do > # do nothing > end > end > > x.report("article_for") do > for i in 0..max do > article_for 'dog' > article_for 'animal' > end > end > > x.report("articlize") do > for i in 0..max do > articlize 'dog' > articlize 'animal' > end > end > > x.report("articlize2") do > for i in 0..max do > articlize2 'dog' > articlize2 'animal' > end > end > end > >