Rails article helper - “a” or “an”

霸气de小男生 提交于 2019-11-30 21:27:39

问题


Does anyone know of a Rails Helper which can automatically prepend the appropriate article to a given string? For instance, if I pass in "apple" to the function it would turn out "an apple", whereas if I were to send in "banana" it would return "a banana"

I already checked the Rails TextHelper module but could not find anything. Apologies if this is a duplicate but it is admittedly a hard answer to search for...


回答1:


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




回答2:


There is now a gem for this: indefinite_article.




回答3:


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)




回答4:


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.




回答5:


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




回答6:


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


来源:https://stackoverflow.com/questions/5381738/rails-article-helper-a-or-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!