2013-02-15 80 views

回答

1
str = "let's upcase last 4 letters" 
length = str.length 
str = str[0..(length-5)] + str[(length-4)..length].upcase 
# let's upcase last 4 letTERS 
+1

您不必先獲取字符串的長度。你可以簡單地做'str [0 ..- 5] + str [-4,4] .upcase'。你可能仍然想檢查原始字符串是否至少有4個字符長。 – Mischa 2013-02-15 05:10:52

+0

謝謝,我還在學Ruby。 – 2013-02-15 05:20:02

+0

不客氣。 – Mischa 2013-02-15 05:24:13

2
s = 'string' 
"#{s[0..-5]}#{s[-4..-1].upcase}" # => stRING 

爲了防止錯誤與字符串長度超過4個字符,你可以做到這一點更短:

s = 'foo' 
s.length > 4 ? "#{s[0..-5]}#{s[-4..-1].upcase}" : s.upcase # => FOO 

時退房Ruby API作出解釋。

0

更新

s = "string" 
s.size > 3 ? s[0..-5]+s[-4..-1].upcase : s.upcase # "stRING" 
相關問題