HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Capitalize all words in sentence string in Ruby

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
allwordssentencecapitalizerubystring

Problem

I have created the following code:

def LetterCapitalize(str)
  str = str.split(" ").each {|word| word.capitalize!}
  str = str.join(" ")
  return str
end


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 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 map than each here.



  • 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.