Reputation: 464
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
Reputation: 67
'foo_bar_baz'.camelize(:lower) # => "fooBarBaz"
'active_record/errors'.camelize(:lower) # => "activeRecord::Errors"
Upvotes: 5
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
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
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
Reputation: 9508
One way:
str = "Hello World"
str[0] = str[0].downcase
str #=> "hello World"
Upvotes: 12
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
Reputation: 1316
def downcase_first_letter(str)
str[0].downcase + str[1..-1]
end
puts downcase_first_letter('Hello World') #=> hello World
Upvotes: 6