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

我想要这样的东西:

"CamelCaseString".to_underscore      

返回“camel_case_string”。

...


当前回答

一行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"

其他回答

一行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"

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"

接收器转换为蛇案:http://rubydoc.info/gems/extlib/0.9.15/String#snake_case-instance_method

这是DataMapper和Merb的支持库。(http://rubygems.org/gems/extlib)

def snake_case
  return downcase if match(/\A[A-Z]+\z/)
  gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').
  gsub(/([a-z])([A-Z])/, '\1_\2').
  downcase
end

"FooBar".snake_case           #=> "foo_bar"
"HeadlineCNNNews".snake_case  #=> "headline_cnn_news"
"CNN".snake_case              #=> "cnn"

如果有人需要在带空格的字符串中应用下划线,并且想要将它们转换为下划线,你可以使用这样的东西

'your String will be converted To underscore'.parameterize.underscore
#your_string_will_be_converted_to_underscore

或者直接使用.parameterize('_'),但请记住,这种方法是不推荐的

'your String will be converted To underscore'.parameterize('_')
#your_string_will_be_converted_to_underscore

有一个Rails内置的方法叫做“下划线”,你可以使用它来实现这个目的

"CamelCaseString".underscore #=> "camel_case_string" 

“下划线”方法通常可以被认为是“camelize”的逆方法。