加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 03:56:02 所属栏目:百科 来源:网络整理
导读:试图将其重构为一行,以使字符串中的所有元音都大写.我尝试使用哈希,但失败了.尽管我尽最大努力查找它,但在 Ruby上还是太新了解任何替代方案.像…. str.gsub!(/ aeiou / def LetterChanges(str) str.gsub!(/a/,"A") if str.include? "a" str.gsub!(/e/,"E")
试图将其重构为一行,以使字符串中的所有元音都大写.我尝试使用哈希,但失败了.尽管我尽最大努力查找它,但在 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读