Alex Rivera | Logout

Ruby equivalent of PHP's ucfirst() function

Asked 2009-09-25T23:22:29.990
10

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"
Edit
Report

1 Answer

6

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
answered 2009-09-26T18:32:29.523

Your Answer