1

This code capitalizes the first letter of each word in a string. Eg "this is a sentence" becomes "This Is A Sentence".

    def capitalize_words(string)
      words = string.split(" ")

      idx = 0
      while idx < words.length
        word = words[idx]

        word[0] = word[0].upcase
        words[idx] = word #this line of code can be made redundant, but why?           

        idx += 1
      end

      return words.join(" ")
    end

In the while statement, I don't understand why the third line is unnecessary. The second line sets the first letter of a word to capital:

  word[0] = word[0].upcase

how does the while statement know to refer back to the previous line

  word = words[idx] 

to put the new capitalised-letter word back into the words array? I thought that when codes are executed, it always works in a forward fashion, please let me know if this understanding is incorrect.

2 Answers 2

3

It's because word variable holds reference for object - the same object that is in words array. So if you modify this object, the object in array is modified also, because it's the same. BTW what you're trying to do here can be done much easier:

string.split(' ').map(&:capitalize).join(' ')

As Stefan suggested: Keep in mind that capitalize not only converts first character to uppercase, but also converts all remaining chars to lowercase. If this is not what you want, you can also do:

string.split(' ').map { |word| word.slice(0, 1).upcase + word.slice(1..-1) }

or use Stefan's solution with regexp:

string.gsub(/\b\w/) { |ch| ch.upcase }

Keep in mind that \b in regexp will 'split' your word not only by spaces, but by any word boudary.

Sign up to request clarification or add additional context in comments.

2 Comments

You could even use a regex and avoid the array: str.gsub(/\b\w/) { |ch| ch.upcase }
BTW, capitalize converts the remaining characters to lowercase.
0

If you are only using ruby then use answer as per @Marek's answer :

string.split(' ').map(&:capitalize).join(' ')  

and If you are using Ruby with Rails then use this:

"this is a sentence".titleize

3 Comments

Please avoid pasting screens with console output - instead, put actual text here.
There is only a Ruby tag and Ruby doesn't provide titleize, so you need to qualify your answer. Also, by providing only a picture of your code, readers cannot grab it for testing.
Note that titleize does much more: it applies inflection rules, replaces _ and - with spaces, removes _id suffixes, converts :: to / and splits camel-cased words.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.