目次(まとめ)

  • ◾️ "capitalize" メソッドを使って、文章や単語の先頭だけを大文字にする

  • ◾️ 関連記事


大文字や小文字が混ざった文章や単語があって、統一感がありません。先頭だけ大文字にしたいのですが、簡単な方法はありますか?

プログラミング言語の1つであるRubyでは、"capitalize" メソッドを使って先頭文字だけ大文字に(残りの文字は小文字に)することができます。

今回の記事では、"capitalize" メソッドの使い方を紹介します。

"capitalize" メソッドを使って、文章や単語の先頭だけを大文字にする

ここでは、以下のような文字列が与えられたとします。

phrase = "It is Not tHe sTroNgest oF tHe sPecIes tHat sUrvives, nOr tHe Most iNtElLigent tHat survives. It Is tHe One tHat IS mOst aDapTable to chanGe."

大文字や小文字が混ざっていて読みにくい文章になっていますが、「種の起源」という名著で有名なイギリスの自然科学者チャールズ・ロバート・ダーウィン(Charles Robert Darwin)が残した言葉です。

意味としては、"いろいろな種(生物)の中で一番強い種が生き残ったわけでも、一番知能が高い種が生き残ったわけでもない。一番変化に適用できた種が生き残ったのだ" となります。

この文章の先頭だけを大文字に変換するためには、以下のように実行します。

p phrase.capitalize
#=> "It is not the strongest of the species that survives, nor the most intelligent that survives. it is the one that is most adaptable to change."

これは、非破壊的メソッドと呼ばれ、この後に以下のように実行すると、元の文字列(大文字と小文字が混ざった文字列)が表示されます。

p phrase
#=> "It is Not tHe sTroNgest oF tHe sPecIes tHat sUrvives, nOr tHe Most iNtElLigent tHat survives. It Is tHe One tHat IS mOst aDapTable to chanGe."

一方で、ビックリマークを付けて、破壊的メソッドとして利用すれば、文字列そのものが置きかわります。

p phrase.capitalize!
#=> "It is not the strongest of the species that survives, nor the most intelligent that survives. it is the one that is most adaptable to change."

p phrase
#=> "It is not the strongest of the species that survives, nor the most intelligent that survives. it is the one that is most adaptable to change."

応用:それぞれの単語の先頭文字を大文字にする

全体の文章が "スペース区切り" であることから、文章を "スペース" を頼りに単語に分割して、それぞれの先頭文字を大文字に変換、さらに、それらを "スペース区切り" でつなぎ合わせることで、それぞれの単語の先頭文字を大文字にすることができます。

例えば、以下のような例になります。

phrase = "It is Not tHe sTroNgest oF tHe sPecIes tHat sUrvives, nOr tHe Most iNtElLigent tHat survives. It Is tHe One tHat IS mOst aDapTable to chanGe."

separated_phrase = phrase.split(" ")   # 文章phraseをスペースで分ける

out = Array.new()
separated_phrase.each do |word|   # それぞれの単語を見ていく
  out << word.capitalize   # 単語の先頭文字を大文字にする
end

p out.join(" ")   # 単語をスペースでつなぎ合わせる
#=> "It Is Not The Strongest Of The Species That Survives, Nor The Most Intelligent That Survives. It Is The One That Is Most Adaptable To Change."

関連記事


今回の記事では、Ruby の "capitalize" メソッドを使って、文章や単語の先頭文字を大文字にする方法を紹介しました。大文字や小文字が混ざった文章や単語に統一感を持たせたいときにご活用ください。

B!