0

Do I need to have more lines of code just to get each word, in a string, to be capitalize using ruby?

h = "hello world and good morning"
h.capitalize #=> Hello world and good morning

I need all words be capitalized. How? Nothing has been mentioned here.

Do I need a messy code to extract each word, using regex, convert to capitalize then put back into string? That sounds messy. Is there a simple method for this?

Sylar
  • 9,953
  • 23
  • 83
  • 157

3 Answers3

3
h = "hello world and good morning" 
h.split.map(&:capitalize).join(' ')
#=> "Hello World And Good Morning"
Andrey Deineko
  • 49,444
  • 10
  • 105
  • 134
1

Here's an alternative method using gsub:

h = "hello world and good morning"
h.gsub(/(?<=\A|\s)\w/, &:upcase)
# => "Hello World And Good Morning"

It basically runs the upcase method on any "word character" (\w) that comes after either the start of the string (\A) or a space (\s).

etdev
  • 514
  • 3
  • 12
0

If there a post elsewhere on this website then you can close this but I have found the answer:

h.split.map(&:capitalize).join(' ')
#=> Hello World And Good Morning
Sylar
  • 9,953
  • 23
  • 83
  • 157