Kirill Zhuravlov
Kirill Zhuravlov

Reputation: 464

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

Upvotes: 7

Views: 8842

Answers (7)

Brian Santanaa
Brian Santanaa

Reputation: 67

'foo_bar_baz'.camelize(:lower)          # => "fooBarBaz"
'active_record/errors'.camelize(:lower) # => "activeRecord::Errors"

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

Upvotes: 5

askrynnikov
askrynnikov

Reputation: 771

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

or

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

Upvotes: 2

Emjey
Emjey

Reputation: 2063

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

Upvotes: 1

Sagar Pandya
Sagar Pandya

Reputation: 9508

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"

Upvotes: 3

Sagar Pandya
Sagar Pandya

Reputation: 9508

One way:

str = "Hello World"
str[0] = str[0].downcase
str #=> "hello World"

Upvotes: 12

Steven Jackson
Steven Jackson

Reputation: 156

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.

Upvotes: 1

jan.zikan
jan.zikan

Reputation: 1316

def downcase_first_letter(str)
  str[0].downcase + str[1..-1]
end

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

Upvotes: 6

Related Questions