Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalize only first character of string and leave others alone? (Rails)

People also ask

How do you capitalize the first character of each word in a string?

At first, you need to split() the string on the basis of space and extract the first character using charAt(). Use toUpperCase() for the extracted character.

How do you capitalize the first letter in Ruby?

Ruby | String capitalize() Method capitalize is a String class method in Ruby which is used to return a copy of the given string by converting its first character uppercase and the remaining to lowercase.

Which string function will capitalize the first character of a string?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.


This should do it:

title = "test test"     
title[0] = title[0].capitalize
puts title # "Test test"

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..."

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..."

str = "this is a Test"
str.sub(/^./, &:upcase)
# => "This is a Test"