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

前端 未结 9 1674
猫巷女王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"
    
    0 讨论(0)
  • 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"
                            ^^^
    
    0 讨论(0)
  • 2020-12-31 13:50

    You probably want to create an extension to the existing titleize function that Rails provides.

    To do so, just include the following file in an initializer, and presto! Supply exceptions on the fly or optionally modify my example to add defaults into the initializer.

    I realize that you didn't want to use Regex, but hey, the actual rails function uses Regex so you might as well keep it in sync.

    Put this file in Rails.root/lib/string_extension.rb and load it in an initializer; or just throw it in the initializer itself.

    UPDATE: modified the REGEX on this thanks to @svoop's suggestion for adding the ending word boundary.

    # 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
    
    0 讨论(0)
  • 2020-12-31 13:50

    If you want not to capitalize and or the, just do the following:

    def titleize(string)
      nocaps = "and"
      string.split(" ").map { |word| nocaps.include?(word) ? word : word.capitalize }.join(" ")
    end
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题