简体   繁体   中英

How to lowercase only the first character of a string in Ruby?

I would like to be able to change the first character of a string to be sure it will be lowercase.

How can I do that?

For example, Hello World -> hello World

One way:

str = "Hello World"
str[0] = str[0].downcase
str #=> "hello World"
def downcase_first_letter(str)
  str[0].downcase + str[1..-1]
end

puts downcase_first_letter('Hello World') #=> hello World

THE FAR BEST ANSWER IS THAT:

'foo_bar_baz'.camelize(:lower) => "fooBarBaz"

reference: https://makandracards.com/makandra/24050-ruby-how-to-camelize-a-string-with-a-lower-case-first-letter

str = "Hello World"

str = str[0,1].downcase + str[1..-1] #hello World

Of course, you can do it more inline too or create a method.

My other answer modifies the existing string, this technique does not:

str  = "Hello World"
str2 = str.sub(str[0], str[0].downcase)

str  #=> "Hello World"
str2 #=> "hello World"
string = 'Hello World'

puts string[0].downcase #This will print just the first letter in the lower case.

Incase you want to print the downcase of first character with rest of the strings use this

string = 'Hello World'
newstring = string[0].downcase + string[1..-1]

puts newstring
str = "Hello World"
str.sub!(/^[[:alpha:]]/, &:downcase)
str #=> "hello World"

or

str = "Hello World"
str2 = str.sub(/^[[:alpha:]]/, &:downcase)
str2 #=> "hello World"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM