sawa
sawa

Reputation: 168101

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"

Upvotes: 3

Views: 1517

Answers (4)

sawa
sawa

Reputation: 168101

Thanks to other answers, I realized some points that I need to be aware of, and also that there is no built in way. I looked into the source of camelize in Active Support of Rails as hinted by Vitaly Zemlyansky, which gave me a hint: that is to use a regex. I decided to use this:

sub(/./){$&.upcase}

Upvotes: 2

Jean-Louis Giordano
Jean-Louis Giordano

Reputation: 1967

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.

Upvotes: 3

steenslag
steenslag

Reputation: 80065

Rather clumsy, but it works:

str = "hello IiPad"
str[0] = str[0].upcase #or .capitalize

Upvotes: 2

Vitaly Zemlyansky
Vitaly Zemlyansky

Reputation: 331

Try this

"hello iPad".camelize

Upvotes: -3

Related Questions