Not a bug or anything, I’m just wondering for which situations is String#capitalize meant for?
it behaves the same way as it would in ruby, but I never understood its purpose/ intention.

I absolutely can see a purpose to just change the first letter of a string to upper case (for example if I want to use a string sometimes at the beginning of a sentence as well as just somewhere in the middle of a sentence), but capitalize not only changes the first letter to upper case, but it also changes all others letters to lower case (which often ruins its use for my former example).

Do you use it? What are situations you use it for?

I would leave the definition of Capitalization to Wikipedia. For title case strings, you can refer to String#titleize which

Returns a new String with the first letter after any space converted to uppercase and every other letter converted to lowercase.


1 Like

a) Probably not (except maybe in some coding challenge or such).
b) I’ve wondered about that myself. So would be interested in any real use case as well.

The implementation of both #capitalize and #titleize is very naive and unaware of any locales or grammar rules.
I’m talking about English here: Usually with title case minor words are not capitalized (e.g. “The Quick Brown Fox Jumps over the Lazy Dog”). Proper nouns are always capitalized (and some other words as well). Some words contain uppercase letters (e.g. “O’Brian”).

There’s so much that goes into these spellings that it’s impossible to express in a simple algorithm. You’d need a complex set of locale-specific rules to even come near a somewhat decent implementation.


String#titleize is used for show a string as title, e.g. used in ECR template.

String#capitalize is used for convert a file name into class/module name.

File.basename("", ".cr").capitalize.camelcase # => EiffelTower

# Only camelcase is not enough for some cases.

File.basename("", ".cr").camelcase # => EiffelToWer

I’ve used it exactly once, and not actually in Crystal, but in Common Lisp (the equivalent function is STRING-CAPITALIZE, does nearly the same thing). It was for my Matrix bot, and was simply for an easter egg where I needed to have it repeat its own name if someone mentions it when using a certain command. This was entirely because I was using the bot’s name in all lowercase way elsewhere in the code and didn’t want two constants, or to hardcode the name in this particular instance.

I later rewrote this bot in Crystal, and didn’t use String#capitalize just because I coded it slightly differently.

1 Like