patternrubyMinor
Capitalize all words in sentence string in Ruby
Viewed 0 times
allwordssentencecapitalizerubystring
Problem
I have created the following code:
This takes in a basic string and capitalizes the first letter of all of the words. It looks kind of awkward to reassign things to
def LetterCapitalize(str)
str = str.split(" ").each {|word| word.capitalize!}
str = str.join(" ")
return str
endThis takes in a basic string and capitalizes the first letter of all of the words. It looks kind of awkward to reassign things to
str twice. What is wrong with my style here, if anything at all?Solution
- Your function name should be in snake_case, not PascalCase. (Thanks @rui.)
- It seems like it would make more sense to use
mapthaneachhere.
- Ruby doesn't need explicit
return.
- You might even want to extend the base string class.
Here's my rendition:
class String
def capitalize_words
this.split.map { |x| x.capitalize }.join(" ")
# or: .map(&:capitalize)
end
end
"this IS a Test".capitalize_words # => "This Is A Test"
Context
StackExchange Code Review Q#56961, answer score: 7
Revisions (0)
No revisions yet.