Search code examples
rubyrspectitle-case

Using title case with Ruby 1.8.7


How can I capitalize certain letters in a string to make it so that only designated words are capitalized.

Must Past These Test: "barack obama" == "Barack Obama" & "the catcher in the rye" == "The Catcher in the Rye"

So far I have a method that will capitalize all words:

#Capitalizes the first title of every word.
def capitalize(words)
     words.split(" ").map {|words| words.capitalize}.join(" ")
end

What are the most efficient next steps I could take to arrive at a solution? Thanks!


Solution

  • You could create a list of the word you don't want to capitalize and do

    excluded_words = %w(the and in) #etc
    
    def capitalize_all(sentence, excluded_words)
      sentence.gsub(/\w+/) do |word|
        excluded_words.include?(word) ? word : word.capitalize
      end
    end
    

    By the way, if you were using Rails and did not need to exclude specific words you could use titleize.

    "the catcher in the rye".titleize
    #=> "The Catcher In The Rye"