Capitalizing titles

前端 未结 2 626
刺人心
刺人心 2021-01-15 03:55

I\'m trying to write a method that will capitalize titles. It should capitalize not every word, but only the big words if you will. Sometimes, it has to capitalize every wor

相关标签:
2条回答
  • 2021-01-15 04:31

    Building off of Josh Voigts comment:

    def titleize(name)
      lowercase_words = %w{a an the and but or for nor of}
      name.split.each_with_index.map{|x, index| lowercase_words.include?(x) && index > 0 ? x : x.capitalize }.join(" ")
    end
    

    You might want make lowercase_words a constant and move it out of the function since they won't ever change.

    0 讨论(0)
  • 2021-01-15 04:38

    This is a very complicated problem, and @johnnycakes answer is a great start, but the list of lowercase_words is not exhaustive. Any preposition of 4 or fewer letters should not be capitalized, such as over, into, on, as, etc. Also, the last word of the title should always be capitalized in addition to the first word.

    Wikipedia has a list of English prepositions. However, this is further complicated by the fact that some words can be both prepositions and verbs, so "I Like You" would capitalize "like" whereas "In like Flynn" would not.

    The Rails titleize method seems to capitalize every word, whereas the titleize gem does a slightly better job of following the actual style guidelines, though still without tackling the preposition problem.

    0 讨论(0)
提交回复
热议问题