2

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"]
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • 4
    For anyone using rails: `["the dog", "the cat", "new york"].map(&:titleize)` – benjessop Sep 03 '20 at 13:50
  • Does this answer your question? [Ruby capitalize every word first letter](https://stackoverflow.com/questions/13520162/ruby-capitalize-every-word-first-letter) – Kal Oct 12 '22 at 23:35

3 Answers3

5

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.

Tom Lord
  • 27,404
  • 4
  • 50
  • 77
2

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

string.split(' ').map(&:capitalize).join(' ')
Paolo Mossini
  • 1,064
  • 2
  • 15
  • 23
  • Your answer is incomplete. You need to write, `array.map { |string| string.split(' ').map(&:capitalize).join(' ') }`. You may prefer `string.split.map...` as that splits on one or more spaces. – Cary Swoveland Sep 03 '20 at 18:44
0

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
Afolabi Olaoluwa
  • 1,898
  • 3
  • 16
  • 37