2

指定された単語のみが大文字になるように、文字列内の特定の文字を大文字にする方法を教えてください。

これらのテストを通過する必要があります: "バラク・オバマ" == "バラク・オバマ" & "ライ麦畑でつかまえて" == "ライ麦畑でつかまえて"

これまでのところ、すべての単語を大文字にする方法があります。

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

解決策に到達するための最も効率的な次のステップは何ですか? ありがとう!

4

2 に答える 2

2

大文字にしたくない単語のリストを作成して、

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"
于 2012-10-29T07:33:55.747 に答える
0

ここに別の解決策があります。それほどきれいではありませんが、すべて大文字のままにしたい頭字語と、私の以前の短縮形の使用のように台無しにしたくない短縮形を扱っています。さらに、最初と最後の単語が大文字になるようにします。

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"
于 2014-12-17T05:42:26.470 に答える