Reputation: 23
I'm trying to capitalize an array, of which some strings consists of multiple words, like for example:
array = ["the dog", "the cat", "new york"]
I tried to use:
array.map(&:capitalize)
but this only capitalized the first letter of each string. Any suggestions? (I'm very new to coding ^_^)
My desired output is:
["The Dog", "The Cat", "New York"]
Upvotes: 2
Views: 1510
Reputation: 1948
Alternately, I would prefer to use Ruby#gsub and make it more of an object that it can be reusable
every other time. But before we get into that, you wanna read up on the following Ruby's String methods:
I believe the method capitalize
and upcase
method can be used and you will see how I used it in my solution below. This will hand extra cases where you have camelcase in your Array, as well as Hyphen:
# frozen_string_literal: true
def converter(string)
string.capitalize.gsub(/\b[a-z]/, &:upcase)
end
array_name = ['the Dog', 'the cat', 'new york', 'SlACKoVeRFLoW', 'OlAoluwa-Afolabi']
print array_name.map(&method(:converter))
As you can see I changed the array a bit. I will advise you use string with single-quotes (i.e '')
and use double-quotes (i.e " ") when you want to do string concatenation
.
Note:
Upvotes: 0
Reputation: 28305
The documentation for String#capitalise
says:
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.
That's not what you're trying to do. So you need to write something custom instead.
For example:
array.map { |string| string.gsub(/\b[a-z]/, &:upcase) }
I'm not clear if/how you plan to handle other input such as all-caps, or hyphenated words, or multiple lines, ... But if your requirements get more detailed then you may need to expand on this implementation.
Upvotes: 5
Reputation: 1098
You can use something like this for each string of your array:
string.split(' ').map(&:capitalize).join(' ')
Upvotes: 2