5
\$\begingroup\$

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"
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

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(&:capitalize).join(' ')
\$\endgroup\$
2
  • \$\begingroup\$ Cool! Exactly, what I was looking for. Thanks a lot. \$\endgroup\$ Commented Jun 5, 2020 at 5:52
  • 5
    \$\begingroup\$ You have presented an alternative solution, but haven't reviewed the code. At least add some remarks on the original code. What do you think of the five lines? Afterwards, please explain your reasoning (why your code is better than the original) so that the author and other readers can learn from your thought process. \$\endgroup\$
    – Zeta
    Commented Jun 5, 2020 at 6:06
1
\$\begingroup\$

I would solve this using a regular expression. like this:

def capitalizeAllWords(str)
  str.gsub(/\b\w/, &:capitalize)
end

where \b matches a work break and \w matches a word character

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.