如何才能在Ruby中以字符串大写形式生成最后4个字符?
答案 0 :(得分: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以获取解释。
答案 1 :(得分: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
答案 2 :(得分:0)
<强>更新强>
s = "string"
s.size > 3 ? s[0..-5]+s[-4..-1].upcase : s.upcase # "stRING"