Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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"
like image 683
Tom Lehman Avatar asked Sep 25 '09 23:09

Tom Lehman


3 Answers

In Rails you have the String#titleize method:

"testing string titleize method".titleize #=> "Testing String Titleize Method"

like image 58
khelll Avatar answered Nov 17 '22 13:11

khelll


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
like image 6
glenn jackman Avatar answered Nov 17 '22 13:11

glenn jackman


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)

like image 16
Greg Campbell Avatar answered Nov 17 '22 13:11

Greg Campbell