本文介绍了将骆驼案例转换为红宝石中的下划线案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有现成的函数可以将驼峰式字符串转换为下划线分隔的字符串?
Is there any ready function which converts camel case Strings into underscore separated string?
我想要这样的东西:
"CamelCaseString".to_underscore
返回camel_case_string".
to return "camel_case_string".
...
推荐答案
Rails 的 ActiveSupport使用以下内容向字符串添加下划线:
Rails' ActiveSupportadds underscore to the String using the following:
class String
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'1_2').
gsub(/([a-zd])([A-Z])/,'1_2').
tr("-", "_").
downcase
end
end
然后你可以做一些有趣的事情:
Then you can do fun stuff:
"CamelCase".underscore
=> "camel_case"
这篇关于将骆驼案例转换为红宝石中的下划线案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!