Rails article helper - “a” or “an”

冷暖自知 提交于 2019-12-01 02:39:45

None that I know of but it seems simple enough to write a helper for this right? Off the top of my head

def indefinite_articlerize(params_word)
    %w(a e i o u).include?(params_word[0].downcase) ? "an #{params_word}" : "a #{params_word}"
end

hope that helps

edit 1: Also found this thread with a patch that might help you bulletproof this more https://rails.lighthouseapp.com/projects/8994/tickets/2566-add-aan-inflector-indefinitize

There is now a gem for this: indefinite_article.

Seems like checking that the first letter is a vowel would get you most of the way there, but there are edge cases:

  • Some people will say "an historic moment" but write "a historic moment".
  • But, it's "a history"!
  • Acronyms and abbreviations are problematic ("An NBC reporter" but "A NATO authority")
  • Words starting with a vowel but pronounced with an initial consonant ("a union")
  • Others?

(source)

I know the following answer goes too much for a practical simple implementation, but in case someone wants to do it with accuracy under some scale of implementation.

The rule is actually pretty much simple, but the problem is that the rule is dependent on the pronounciation, not spelling:

If the initial sound is a vowel sound (not necessarily a vowel letter), then prepend 'an', otherwise prepend 'a'.

Referring to John's examples:

'an hour' because the 'h' here is a vowel sound, whereas 'a historic' because the 'h' here is a consonant sound. 'an NBC' because the 'N' here is read as 'en', whereas 'a NATO' because the 'N' here is read as 'n'.

So the question is reduced to finding out: "when are certain letters pronounced as vowel sounds". In order to do that, you somehow need to access a dictionary that has phonological representations for each word, and check its initial phoneme.

Obie

Look into https://deveiate.org/code/linguistics/ - it provides handling of indefinite articles and much more. I've used it successfully on many projects.

I love the gem if you want a comprehensive solution. But if you just want tests to read more nicely, it is helpful to monkey patch String to follow the standard Rails inflector pattern:

class String
  def articleize
    %w(a e i o u).include?(self[0].downcase) ? "an #{self}" : "a #{self}"
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!