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"
Peilonrayz
44.4k7 gold badges80 silver badges157 bronze badges
asked Jun 5, 2020 at 5:20
\$\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(' ')
answered Jun 5, 2020 at 5:28
\$\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\$ 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

answered Jun 12, 2020 at 17:53
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.