Method: Titleize#titleize

Defined in:
lib/titleize.rb

#titleize(title) ⇒ Object

Capitalizes most words to create a nicer looking title string.

The list of “small words” which are not capped comes from the New York Times Manual of Style, plus ‘vs’ and ‘v’.

"notes on a scandal" # => "Notes on a Scandal"
"the good german"    # => "The Good German"


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/titleize.rb', line 21

def titleize(title)
  title = title.dup
  title.downcase! unless title[/[[:lower:]]/]  # assume all-caps need fixing

  phrases(title).map do |phrase|
    words = phrase.split
    words.map do |word|
      def word.capitalize
        # like String#capitalize, but it starts with the first letter
        self.sub(/[[:alpha:]].*/) {|subword| subword.capitalize}
      end

      case word
      when /[[:alpha:]]\.[[:alpha:]]/  # words with dots in, like "example.com"
        word
      when /[-‑]/  # hyphenated word (regular and non-breaking)
        word.split(/([-‑])/).map do |part|
          SMALL_WORDS.include?(part) ? part : part.capitalize
        end.join
      when /^[[:alpha:]].*[[:upper:]]/ # non-first letter capitalized already
        word
      when /^[[:digit:]]/  # first character is a number
        word
      when words.first, words.last
        word.capitalize
      when *(SMALL_WORDS + SMALL_WORDS.map {|small| small.capitalize })
        word.downcase
      else
        word.capitalize
      end
    end.join(" ")
  end.join(" ")
end