Tom Lehman Tom Lehman - 7 months ago 70
Ruby Question

Ruby equivalent of PHP's ucfirst() function

What's the best way in Ruby (with Rails, if relevant) to capitalize the first letter of a string?

Note that

is not what I want since, in addition to capitalizing the first letter of the string, this function makes all other characters lowercase (which I don't want -- I'd like to leave them untouched):

>> "a A".capitalize
=> "A a"


You can use "sub" to get what you want (note: I haven't tested this with multibyte strings)

"a A".sub(/^(\w)/) {|s| s.capitalize}

(and you can of course monkeypatch String to add this as a method if you like)