I wanted to capitalize a string, and tried using String.capitalize()
.
That generally works well, until you try to capitalize a word like ATM
, which then comes out as Atm
.
That is correct according to the documentation, as it states that String.capitalize()
does this:
Converts the first character in the given string to uppercase and the remainder to lowercase according to
mode
. [emphasis mine]
Now that is not what I expected from a function called capitalize()
. I naïvely thought that would only touch the first letter, as String.capitalize does in Python and similarly named functions does in other programming languages.
Elixir is probably mimicking Ruby here, and the point of this post is not to say that the implementation is wrong, it’s too late to change now anyway.
However, it would be handy if there was a :first_letter_only
or similar mode
, that would only touch the first letter, so developers everywhere won’t have to write their own capitalize function to be able to safely capitalize words without mangling abbreviations.
(If you come across this topic wanting to just capitalize the first letter, you can use Don’t do this, see comment from josevalim below.String.Casing.titlecase_once(word, nil)
, although this is a little undocumented).