gpt4 book ai didi

ruby - 将多个 gsub 语句重构为 1

转载 作者:数据小太阳 更新时间:2023-10-29 07:23:45 25 4
gpt4 key购买 nike

尝试将其重构为一行以使字符串中的所有元音字母大写。我尝试使用哈希,但失败了。尽管我已尽最大努力进行查找,但对 Ruby 仍然太陌生,不知道任何替代方案。像.... str.gsub!(/aeiou/

def LetterChanges(str)
str.gsub!(/a/, "A") if str.include? "a"
str.gsub!(/e/, "E") if str.include? "e"
str.gsub!(/i/, "I") if str.include? "i"
str.gsub!(/o/, "O") if str.include? "o"
str.gsub!(/u/, "U") if str.include? "u"
puts str
end

最佳答案

最好的办法是

str.tr('aeiou', 'AEIOU')

String#tr

Returns a copy of str with the characters in from_str replaced by the corresponding characters in to_str. If to_str is shorter than from_str, it is padded with its last character in order to maintain the correspondence.

关于ruby - 将多个 gsub 语句重构为 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24045773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com