Question with two last names and .capitalize


#1

I’m not so much as stuck but curious with something, I’m putting two last names with the method .capitalize

so when I follow the code and enter the last name, “palma monteñez” at the end of the program it returns, “Palm montañez” how do I capitialize the second name? (I think I would be correct if I followed the same syntax if i wanted the third name, fourth, etc.)

Thank you very much for your help



print "What's your last name?"
last_name = gets.chomp
last_name1 = last_name.capitalize
last_name.capitalize!



#2

The .capitalize function capitalizes just the first letter of the first word and then makes all the rest of the characters lowercase. You discovered that in your above code.

There are multiple ways to capitalize every word in a given string such as:

puts last_name.split(/ |\_/).map(&:capitalize).join(" ")
puts last_name.gsub(/\w+/, &:capitalize)

But then there are edge cases where these do not work, such as McDonald or McHenry. So then we can change it to:

puts 'ronald mcDonald'.gsub(/\b\w/, &:capitalize)

That works until you have a word that is in all caps like PALMA.

Here’s an experiment for you to play with and see the different edge cases:

If you are bold and want to dive into this further, check out how Rails handles the titleize functionality. It’s part of the ActiveSupport::Inflector module.


#3

Wow, thanks a lot! I will be sure to investigate all this now!
thanks again!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.