elixir

Why does Elixir's String.capitalize() function lowercase remaining letters?


Elixir's String.capitalize/2 function "converts the first character in the given string to uppercase and the remainder to lowercase". Would it not be more intuitive to capitalize the first character and leave the remaining characters unchanged? Maybe there is some reasoning I am missing?

The current implementation results in the local ATM -> The local Atm, forgotten PIN -> Forgotten Pin etc.


Solution

  • Here is a solution that does not require calling the undocumented implementation specific String.Casing.

    with <<c :: utf8, rest :: binary>> <- "the local ATM",
      do: String.upcase(<<c>>) <> rest
    
    #⇒ "The local ATM"
    

    The above works with unicode characters as well (both composed and decomposed):

    with <<c :: utf8, rest :: binary>> <- "über BVG",
      do: String.upcase(<<c>>) <> rest
    
    #⇒ "Über BVG"