Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalizing a sentence

Is there a method (perhaps in some library from Rails) or an easy way that capitalizes the first letter of a string without affecting the upper/lower case status of the rest of the string? I want to use it to capitalize error messages. I expect something like this:

"hello iPad" #=> "Hello iPad"
like image 260
sawa Avatar asked Jul 12 '26 04:07

sawa


1 Answers

There is a capitalize method in Ruby, but it will downcase the rest of the string. You can write your own otherwise:

class String
  def capitalize_first
    (slice(0) || '').upcase + (slice(1..-1) || '')
  end

  def capitalize_first!
    replace(capitalize_first)
  end
end

Edit: Added capitalize_first! variant.

like image 191
Jean-Louis Giordano Avatar answered Jul 15 '26 23:07

Jean-Louis Giordano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!