Class: Titlecaser::TitleCase
- Inherits:
-
Object
- Object
- Titlecaser::TitleCase
- Defined in:
- lib/titlecaser.rb
Instance Method Summary collapse
- #convert ⇒ Object
-
#initialize(string) ⇒ TitleCase
constructor
A new instance of TitleCase.
Constructor Details
#initialize(string) ⇒ TitleCase
7 8 9 |
# File 'lib/titlecaser.rb', line 7 def initialize(string) @string = string end |
Instance Method Details
#convert ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/titlecaser.rb', line 11 def convert words = @string.split(' ') previous_word = nil converted_words = words.map.with_index do |word, index| # Take any initial punctuation character (e.g. quotes) and store it to rejoin later starting_punctuation = word[/\A[^\p{L}0-9]/].to_s # Take the rest of the word word = word[starting_punctuation.length..-1] # If it's already capitalized and NOT a minor word, leave everything as-is if already_capitalized?(word) && !minor_word?(word) word = starting_punctuation + word else # Otherwise, determine if it's a major word and handle appropriately if major_word?(word, index, previous_word) word = starting_punctuation + capitalize_word(word) else # Force a downcase if need be word = starting_punctuation + word.downcase end end # Store the word for the next iteration, as it may have useful trailing punctuation previous_word = word end # Put it all back together converted_words.join(' ') end |