On Nov 6, 2011, at 1:50 PM, Ryan Davis wrote:

>=20
> On Nov 6, 2011, at 12:59 , steve ross wrote:
>=20
>> Sorry to be late to the party on this one, but a regex seems a bit of =
a big hammer. How about:
>>=20
>> def article_for(noun)
>> article =3D %w(a e i o u).include?(noun[0..0]) ? 'an' : 'a'
>> "#{article} #{noun}"
>> end
>>=20
>> irb(main):022:0> article_for 'dog'
>> =3D> "a dog"
>> irb(main):023:0> article_for 'animal'
>> =3D> "an animal"
>=20
> 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):
>=20

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 =3D~ 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'
>=20
> # # of iterations =3D 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)
>=20
> def article_for(noun)
> article =3D %w(a e i o u).include?(noun[0..0]) ? 'an' : 'a'
> "#{article} #{noun}"
> end
>=20
> def articlize noun
>  article =3D /^[aeiou]/ =3D~ noun ? 'an' : 'a'
>  "#{article} #{noun}"
> end
>=20
> # just to see if this makes much of a difference
> def articlize2 noun
>  "#{/^[aeiou]/ =3D~ noun ? 'an' : 'a'} #{noun}"
> end
>=20
> max =3D (ARGV.shift || 1_000_000).to_i
>=20
> puts "# of iterations =3D #{max}"
> Benchmark::bm(20) do |x|
>  x.report("null_time") do
>    for i in 0..max do
>      # do nothing
>    end
>  end
>=20
>  x.report("article_for") do
>    for i in 0..max do
>      article_for 'dog'
>      article_for 'animal'
>    end
>  end
>=20
>  x.report("articlize") do
>    for i in 0..max do
>      articlize 'dog'
>      articlize 'animal'
>    end
>  end
>=20
>  x.report("articlize2") do
>    for i in 0..max do
>      articlize2 'dog'
>      articlize2 'animal'
>    end
>  end
> end
>=20
>=20