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): 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