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"
2 Answers 2
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(' ')
-
\$\begingroup\$ Cool! Exactly, what I was looking for. Thanks a lot. \$\endgroup\$michael.zech– michael.zech2020年06月05日 05:52:20 +00:00Commented 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– Zeta2020年06月05日 06:06:00 +00:00Commented Jun 5, 2020 at 6:06
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