Using title case with Ruby 1.8.7

家住魔仙堡 提交于 2019-12-02 03:35:18

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"

Here is another solution. It's not so pretty, but it deals with acronyms that you want to remain all caps and contractions that you Don'T want to be mangled like my previous use of the contraction don't. Beyond that, it ensures that your first and last word is capitalized.

class String
  def titlecase
    lowerCaseWords = ["a", "aboard", "about", "above", "across", "after", "against", "along", "amid", "among", "an", "and", "around", "as", "at", "before", "behind", "below", "beneath", "beside", "besides", "between", "beyond", "but", "by", "concerning", "considering", "d", "despite", "down", "during", "em", "except", "excepting", "excluding", "following", "for", "from", "in", "inside", "into", "it", "ll", "m", "minus", "near", "nor", "of", "off", "on", "onto", "opposite", "or", "outside", "over", "past", "per", "plus", "re", "regarding", "round", "s", "save", "since", "t", "than", "the", "through", "to", "toward", "towards", "under", "underneath", "unlike", "until", "up", "upon", "ve", "versus", "via", "with", "within", "without", "yet"]
    titleWords = self.gsub( /\w+/ )
    titleWords.each_with_index do | titleWord, i |
      if i != 0 && i != titleWords.count - 1 && lowerCaseWords.include?( titleWord.downcase )
        titleWord
      else
        titleWord[ 0 ].upcase + titleWord[ 1, titleWord.length - 1 ]
      end
    end
  end
end

Here are some examples of how to use it

puts 'barack obama'.titlecase # => Barack Obama
puts 'the catcher in the rye'.titlecase # => The Catcher in the Rye
puts 'NASA would like to send a person to mars'.titlecase # => NASA Would Like to Send a Person to Mars
puts 'Wayne Gretzky said, "You miss 100% of the shots you don\'t take"'.titlecase # => Wayne Gretzky Said, "You Miss 100% of the Shots You Don't Take"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!