0

Is there a method that works similar to singularize to prepend "a" or "an according to the word?

  • like f(apple) # => an apple
  • f(carpet) #=> a carpet
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244

1 Answers1

5

Look here http://deveiate.org/projects/Linguistics/wiki/English and check out this question

If you need something simpler, something that will for instance prepend "an" if a word starts with vowel, you can use my one liner:

String.class_eval { def prepend; %w(a e i o u).include?(downcase.first) ? "an #{self}" : "a #{self}"; end }

Put this in a file prepend.rb in config/initializers folder of your application.

Then you will be able to use

"carrot".prepend => "a carrot"
"apple".prepend => "an apple"
Community
  • 1
  • 1
shime
  • 8,746
  • 1
  • 30
  • 51
  • 3
    I like it. I would humbly suggest using a_or_an for the name. prepend is wonderfully generic but perhaps too much so. carrot.a_or_an is going to be pretty clear to casual code readers :) If we are talking about others things like 'This' or somethings sure, but for now KISS :) – Michael Durrant Nov 19 '11 at 16:18
  • Great solution! However, I called my function "with_article". Cheers! – vanboom Oct 29 '13 at 15:35
  • It will fail when it comes to a string like `hour` which do not start with vowel. – Shailesh Kalamkar Jun 30 '16 at 17:30
  • Similarly, it will fail for some words that start with one of those 5 letters but take "a", like `university`. – Masa Sakano Mar 07 '18 at 15:12