Capitalize only first character of string and leave others alone? (Rails)
Solution 1:
This should do it:
title = "test test"
title[0] = title[0].capitalize
puts title # "Test test"
Solution 2:
Titleize will capitalise every word. This line feels hefty, but will guarantee that the only letter changed is the first one.
new_string = string.slice(0,1).capitalize + string.slice(1..-1)
Update:
irb(main):001:0> string = "i'm from New York..."
=> "i'm from New York..."
irb(main):002:0> new_string = string.slice(0,1).capitalize + string.slice(1..-1)
=> "I'm from New York..."
Solution 3:
You can use humanize. If you don't need underscores or other capitals in your text lines.
Input:
"i'm from New_York...".humanize
Output:
"I'm from new york..."
Solution 4:
str = "this is a Test"
str.sub(/^./, &:upcase)
# => "This is a Test"
Solution 5:
As of Rails 5.0.0.beta4 you can use the new String#upcase_first
method or ActiveSupport::Inflector#upcase_first
to do it. Check this blog post for more info.
So
"i'm from New York...".upcase_first
Will output:
"I'm from New York..."