2016-11-22 72 views
0

我怎樣才能在小寫字母串紅寶石只有第一個字符?我找到的所有現有方法都無法工作。如何小寫只有第一個字符的字符串紅寶石

input "Hello World" 
output "hello World" 
+1

您可能需要使用包括在輸出大寫字符的例子。 – Stefan

+0

@CarySwoveland我想只將第一個字母轉換爲小寫。這是更好地創建具有所需性能 –

回答

8

方式一:

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

不'downcase一個新的字符串!'(要認識到它返回'nil'如果第一個字母是小寫)? –

+0

@CarySwoveland很好的觀察。 –

+0

比我的更簡潔。我喜歡這個解決方案。 –

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

puts downcase_first_letter('Hello World') #=> hello World 
1
str = "Hello World" 

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

當然,你可以做到這一點更直列過或創建一個方法。

1

我的另一個答案修改現有的字符串,該技術不:

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

str #=> "Hello World" 
str2 #=> "hello World" 
+0

你的兩個答案是毫米級的,應該合併成一個答案。 –

+0

@CarySwoveland我想使用sub'和分配的'來保證這個新的變量是(哪怕是微小)不同的答案。 –

0
string = 'Hello World' 

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

櫃面要打印休息第一個字符的downcase字符串的使用

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

puts newstring