Ruby: Titleize: How do I ignore smaller words like 'and', 'the', 'or, etc

前端 未结 9 1877
猫巷女王i
猫巷女王i 2020-12-31 13:13
def titleize(string)
  string.split(\" \").map {|word| word.capitalize}.join(\" \")
end

This titleizes every single word, but how do I capture cert

9条回答
  •  北荒
    北荒 (楼主)
    2020-12-31 14:07

    Some titles have edge cases (pun intended) that you might need to consider.

    For example, small words at the start of a title or after punctuation often should be capitalized (e.g. "The Chronicles of Narnia: The Lion, the Witch and the Wardrobe" which has both).

    One may also want/need to force small words to lower-case, so that input like "Jack And Jill" gets rendered to "Jack and Jill".

    Sometimes you may also need to detect when a word (typically brand names) must retain unusual capitalization e.g. "iPod", or acronyms e.g. "NATO", or domain names, "example.com".

    To properly handle such cases, the titleize gem is your friend, or should at least supply the basis for a complete solution.

提交回复
热议问题