Ruby function to capitalize all words in a string The task is to write a function, which capitalize the first letter of all words in a string. For this we'll class a word as any characters separated by a blank. Because the standard String.capitalize method only capitalizes the first character of the string I have written the following.

Could the task be accomplished with writing less code? Any other improvements-suggestions concerning the function?

Here's the code I have written:

def capitalizeAllWords(str)
    caps = str.split(" ").map do |word| 
        word.capitalize
    end
    caps.join " "
end

puts capitalizeAllWords "Red orange green blue indigo violet" 
# Prints: "Red Orange Green Blue Indigo Violet"
You could make it a one liner. If you want to get fancy checkout Rail's implementation https://apidock.com/rails/v5.2.3/ActiveSupport/Inflector/titleize

str.split.map(&amp;:capitalize).join(' ')