Kathan
Kathan

Reputation: 1458

Capitalize First Letter of all Words and Keep Already Capitalized

Using rails 4, and having trouble finding documentation on this. I would like to capitalize the first letter of each word in a string but keep already capitalized letters.

I would like the following outputs:

how far is McDonald's from here? => How Far Is McDonald's From Here?

MDMA is also known as molly => MDMA Is Also Known As Molly

i drive a BMW => I Drive A BMW

I thought .titleize would do it, but that will turn BMW into Bmw. Thank you for any help.

Upvotes: 6

Views: 1442

Answers (3)

Dorian
Dorian

Reputation: 9185

to capitalize only the first letter while preserving existing capitalization:

your_string.then { |s| s[0].upcase + s[1..-1] }

Upvotes: 0

potashin
potashin

Reputation: 44601

You can try the following:

a.split.map{|x| x.slice(0, 1).capitalize + x.slice(1..-1)}.join(' ')
# or
a.split.map{|x| x[0].upcase + x[1..-1]}.join(' ')
#=> ["MDMA Is Also Known As Molly",
     "How Far Is McDonald's From Here?",
     "I Drive A BMW"]

Demonstration

Upvotes: 7

Ryan K
Ryan K

Reputation: 4053

You can do a custom method like this:

string = "your string IS here"
output = []
string.split(' ').each do |word|
  if word =~ /[A-Z]/
    output << word
  else
    output << word.capitalize
  end
end
output.join(' ')

Of course, this will not change a word like "tEST" or "tEst" because it has at least one capital letter in it.

Upvotes: 1

Related Questions