Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - simple way to convert the first letter of string to downcase

Tags:

string

ruby

jruby

Is there a simple way to convert the first letter of a string to downcase? String#capitalize modifies the entire string. Sure, I can remove the first letter, downcase it and then append it in the beginning. But it seems kinda silly, is there a simpler way?

Note: I'll be dealing with only English words.

Edit: str[0] = str[0].downcase doesn't work in JRuby 1.6 :(

Edit 2: In the end I settled on this:

word = "ABC"
first_capital_letter = word.match(/^([A-Z])/).to_s
 if(first_capital_letter)
   word = word.sub(first_capital_letter, first_capital_letter.downcase)
   puts word
end
like image 915
huhucat Avatar asked Dec 02 '22 01:12

huhucat


1 Answers

If you really don't want to downcase the first letter and re-append it you could do str.gsub(/^\w{1}/) { |m| m.downcase } but that seems silly.

like image 152
Michael Kohl Avatar answered Dec 27 '22 08:12

Michael Kohl