是否有任何现成的函数转换驼峰大小写字符串为下划线分隔字符串?

我想要这样的东西:

"CamelCaseString".to_underscore      

返回“camel_case_string”。

...


当前回答

我有麻烦运行“CamelCaseString”。在rake任务中使用下划线。这帮助了我:

ActiveSupport::Inflector.underscore "CamelCaseString"
=> "camel_case_string"

当然,您需要使用ActiveSupport

其他回答

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"

下面是Rails是如何做到的:

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

我有麻烦运行“CamelCaseString”。在rake任务中使用下划线。这帮助了我:

ActiveSupport::Inflector.underscore "CamelCaseString"
=> "camel_case_string"

当然,您需要使用ActiveSupport

一行Ruby实现:

class String
   # ruby mutation methods have the expectation to return self if a mutation occurred, nil otherwise. (see http://www.ruby-doc.org/core-1.9.3/String.html#method-i-gsub-21)
   def to_underscore!
     gsub!(/(.)([A-Z])/,'\1_\2')
     downcase!
   end

   def to_underscore
     dup.tap { |s| s.to_underscore! }
   end
end

所以“SomeCamelCase”。To_underscore # =>"some_camel_case"

你可以使用

"CamelCasedName".tableize.singularize

或者只是

"CamelCasedName".underscore

这两种方法都会产生“camel_cased_name”。你可以在这里查看更多细节。