使用Ruby 1.8.7的标题案例

如何将字符串中的某些字母大写以使其仅使指定的单词大写。

必须通过这些测试:“barack obama”==“Barack Obama”和“黑麦中的守望者”==“麦田里的守望者”

到目前为止,我有一个方法可以将所有单词大写:

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

我可以采取哪些最有效的后续步骤来达成解决方案? 谢谢!

您可以创建一个您不想大写的单词列表

 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 

顺便说一句,如果您使用Rails并且不需要排除特定单词,则可以使用titleize

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

这是另一种解决方案。 它不是那么漂亮,但它处理的缩写词你想要保持所有的帽子和收缩,你不想像我之前使用的收缩那样被破坏。 除此之外,它确保您的第一个和最后一个词被大写。

 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 

以下是如何使用它的一些示例

 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"