gpt4 book ai didi

ruby - 如何实现 String 方法的破坏性版本?

转载 作者:太空宇宙 更新时间:2023-11-03 17:05:11 25 4
gpt4 key购买 nike

我复制了以下 underscore 方法的实现,以将驼峰式字符串转换为单词由下划线分隔的字符串:

class String
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end

我如何实现一种方法,例如 underscore!,以破坏性地执行相同的操作,即就地修改字符串?

最佳答案

使用 String#replace方法:

class String
def underscore
# same as before
end

def underscore!
replace(underscore)
end
end

s = 'FooBar'
s.underscore!
puts s
# 'foo_bar'

关于ruby - 如何实现 String 方法的破坏性版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22554177/

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