Search code examples
rubyarraysstringcapitalize

Capitalizing words in an array, Ruby


I'm going through App Academy's Ruby Prep questions, and I want to know why this solution works. It appears that the words array is never altered and yet the method works. Is this a glitch in the matrix, or is it right under my nose?

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

  idx = 0
  while idx < words.length
    word = words[idx]
    word[0] = word[0].upcase
    idx += 1
  end

  return words.join(" ")
end

Solution

  • String#[]= is a mutating operation. To illustrate using a concise, contained excerpt from your code:

    word = "foo"
    word[0] = word[0].upcase  # <-- verbatim from your code
    word #=> "Foo"
    

    word is still the same exact object contained in the array words (arrays simply contain references to objects, not the data within them), but it has been mutated in-place. It’s generally best to avoid mutations whenever possible as it makes it non-obvious what is happening (as you can see).

    Your code could also be more concisely written using map & capitalize (and without any mutations):

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