且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在ruby中将骆驼大小写转换为下划线大小写

更新时间:2023-02-15 17:37:45

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"