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

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

    If you throw this into config/initializers into a new file (you can name it anything like string.rb), you can call your custom functions to any string. Make sure you restart, and then you will be able to run below like ex) "anystring".uncapitalize_puncs

    This is easier than messing around trying to change the default code of titleize. So now, you can just call @something.title.titleize.uncapitalize_puncs

    class String
    
        def uncapitalize_puncs
            puncs = ["and", "the", "to", "of", "by", "from", "or"]
            array = self.split(" ")
            array.map! do |x| 
                if puncs.include? x.downcase
                    x.downcase
                else
                    x
                end
            end
            return array.join(" ")
        end
    
    end
    

提交回复
热议问题