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

前端 未结 9 1675
猫巷女王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.

    0 讨论(0)
  • 2020-12-31 14:09

    This is pretty straightforward, just add a condition when you call captalize:

    $nocaps = ['Jack', 'Jill']
    
    def titleize(string)
      string.split(" ").map {|word| word.capitalize unless $nocaps.include?(word)}.join(" ")
    end
    

    The global variables are contrived for this example, it would probably be an instance variable in your real application.

    0 讨论(0)
  • 2020-12-31 14:12

    metodo capitalize para títulos

    def capitalizar_titulo(string)
        words_not_to_capitalize = ["a","e","i","o","u","ao","aos", "as", "nos","nós","no","na","mas", "mes", "da", "de", "di", "do", "das", "dos"]
        s = string.split.each{|str| str.capitalize! unless words_not_to_capitalize.include? (str.downcase) }
        s[0].capitalize + " " + s[1..-1].join(" ")
      end
    
    0 讨论(0)
提交回复
热议问题