Search code examples
arraysrubycapitalize

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"]

Solution

  • 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.