有没有现成的函数可以将驼峰字符串转换为下划线分隔的字符串?
我想要这样的东西:
"CamelCaseString".to_underscore
返回“camel_case_string”。
...
最佳答案
Rails' ActiveSupport 使用以下命令为字符串添加下划线:
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
然后你可以做一些有趣的事情:
"CamelCase".underscore
=> "camel_case"
关于ruby-on-rails - 在ruby中将 Camel 大小写转换为下划线大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1509915/