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

前端 未结 9 1787
猫巷女王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 13:46

    titleize("the matrix or titanic")
    
    def titleize(string)
      no_cap = ["and", "or", "the", "over", "to", "the", "a", "but"]
      string.split(" ").map { |word| no_cap.include?(word) ? word : 
      word.capitalize }.join(" ")
    end
    

    result:

    "the Matrix or Titanic"
    

提交回复
热议问题