What's the best way in Ruby (with Rails, if relevant) to capitalize the first letter of a string?
Note that String#capitalize
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"
In Rails you have the String#titleize
method:
"testing string titleize method".titleize #=> "Testing String Titleize Method"
Upper case the first char, and save it back into the string
s = "a A"
s[0] = s[0,1].upcase
p s # => "A A"
Or,
class String
def ucfirst!
self[0] = self[0,1].upcase
self
end
end
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With