在ruby中将骆驼大小写转换为下划线大小写 [英] Converting camel case to underscore case in ruby
本文介绍了在ruby中将骆驼大小写转换为下划线大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有现成的函数可以将驼峰字符串转换为下划线分隔的字符串?
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' ActiveSupport adds 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"
这篇关于在ruby中将骆驼大小写转换为下划线大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文