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

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

    The answer of @codenamev is not quite doing the job:

    EXCLUSIONS = %w(a the and or to)
    "and the answer is all good".titleize(exclude: EXCLUSIONS)
    # => "And the Answer Is all Good"
                            ^^^
    

    Exclusions should match trailing word boundaries. Here's an improved version:

    # encoding: utf-8
    class String
      def titleize(options = {})
        exclusions = options[:exclude]
    
        return ActiveSupport::Inflector.titleize(self) unless exclusions.present?
        self.underscore.humanize.gsub(/\b(['’`]?(?!(#{exclusions.join('|')})\b)[a-z])/) { $&.capitalize }
      end
    end
    
    "and the answer is all good".titleize(exclude: EXCLUSIONS)
    # => "And the Answer Is All Good"
                            ^^^
    

提交回复
热议问题