Steven Visser
Steven Visser

Reputation: 23

Capitalize each word in an array

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

Answers (3)

Afolabi Olaoluwa
Afolabi Olaoluwa

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:

  1. String#gsub Method
  2. String#capitalize Method
  3. Read this blog too to have a view of how you can use gsub

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:

  1. I believe my solution can be extended further. It can be reviewed to suit all kinds of productivity and edge cases. So you can find such array and test with it, and extent the solution further.
  2. I used Ruby 2.7.1

Upvotes: 0

Tom Lord
Tom Lord

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

Paolo Mossini
Paolo Mossini

Reputation: 1098

You can use something like this for each string of your array:

string.split(' ').map(&:capitalize).join(' ')

Upvotes: 2

Related Questions