views:

542

answers:

6

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"
A: 

Have a look at this.

capitalizing-first-letter-of-each-word

There's not an inbuilt function. You need to split the letters and rejoin or try Rails' String#titleize and see if it does what you want.

Trevor Tippins
+4  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)

Greg Campbell
A: 

what about styling that via CSS and voila - no scripting needed!

p:first-letter (font-size: 16px;}

ps: i assume you want to print that later on screen and not to save it in DB or such use - in that case, you can ignore this answer.

dusoft
Note that there is actually a text-transform property in CSS which can do capitalization : http://www.w3.org/TR/CSS2/text.html#caps-prop .
Greg Campbell
yeah, i love downvotes, use them a lot, seed them everywhere. specially for clever responses that save you a programming and server time.
dusoft
I didn't downvote you, but I'd guess you're getting downvotes in part because your solution would turn a lowercase 'a' into a large lowercase 'a' rather than a capital 'A'.
Greg Campbell
+1  A: 

In Rails you have the String#titleize method:

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

khelll
+1  A: 

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
glenn jackman
A: 

If you don't want to modify the original string, you can do it this way:

class String
  def ucfirst
    str = self.clone
    str[0] = str[0,1].upcase
    str
  end
end
Max Masnick