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

前端 未结 9 1800
猫巷女王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:01

    Here is my little code. You can refractor it into a few lines.

    def titleize(str)
        str.capitalize!  # capitalize the first word in case it is part of the no words array
        words_no_cap = ["and", "or", "the", "over", "to", "the", "a", "but"]
        phrase = str.split(" ").map {|word| 
            if words_no_cap.include?(word) 
                word
            else
                word.capitalize
            end
        }.join(" ") # I replaced the "end" in "end.join(" ") with "}" because it wasn't working in Ruby 2.1.1
      phrase  # returns the phrase with all the excluded words
    end
    

提交回复
热议问题