w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How do I capitalize all words in a string apart from small words in the middle and in the beginning?

It’s easiest to just forget about the special case of the first letter initially and then handle it after doing everything else:

def title(sentence)
  small_words = %w[on the and]

  capitalized_words = sentence.split(' ').map do |word|
    small_words.include?(word) ? word : word.capitalize

  capitalized_words.join(' ')

This also capitalizes any “small word” at the beginning, not just “the”—but I think that’s probably what you want anyway.

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.