在骆驼转换驼峰案件下划线案件

有没有什么现成的函数将驼峰string转换为下划线分隔的string?

我想要这样的东西:

"CamelCaseString".to_underscore 

返回“camel_case_string”。

Rails的ActiveSupport使用下面的代码为String添加下划线:

 class String def underscore self.gsub(/::/, '/'). gsub(/([AZ]+)([AZ][az])/,'\1_\2'). gsub(/([az\d])([AZ])/,'\1_\2'). tr("-", "_"). downcase end end 

那么你可以做有趣的东西:

 "CamelCase".underscore => "camel_case" 

您可以使用

“CamelCasedName” .tableize.singularize

要么

“CamelCasedName” .underscore

两者都会给你

camel_cased_name

你可以在这里查看

单线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!(/(.)([AZ])/,'\1_\2') downcase! end def to_underscore dup.tap { |s| s.to_underscore! } end end 

所以"SomeCamelCase".to_underscore # =>"some_camel_case"

有一个Rails内置的方法称为“下划线”,你可以使用这个目的

 "CamelCaseString".underscore #=> "camel_case_string" 

“下划线”方法通常可以被认为是“驼化”

Rails是如何做到这一点的 :

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

接收器转换为蛇情况: 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[AZ]+\z/) gsub(/([AZ]+)([AZ][az])/, '\1_\2'). gsub(/([az])([AZ])/, '\1_\2'). downcase end "FooBar".snake_case #=> "foo_bar" "HeadlineCNNNews".snake_case #=> "headline_cnn_news" "CNN".snake_case #=> "cnn" 

从Ruby Facets中检查蛇形

以下情况处理,如下所示:

 "SnakeCase".snakecase #=> "snake_case" "Snake-Case".snakecase #=> "snake_case" "Snake Case".snakecase #=> "snake_case" "Snake - Case".snakecase #=> "snake_case" 

来自: https : //github.com/rubyworks/facets/blob/master/lib/core/facets/string/snakecase.rb

 class String # Underscore a string such that camelcase, dashes and spaces are # replaced by underscores. This is the reverse of {#camelcase}, # albeit not an exact inverse. # # "SnakeCase".snakecase #=> "snake_case" # "Snake-Case".snakecase #=> "snake_case" # "Snake Case".snakecase #=> "snake_case" # "Snake - Case".snakecase #=> "snake_case" # # Note, this method no longer converts `::` to `/`, in that case # use the {#pathize} method instead. def snakecase #gsub(/::/, '/'). gsub(/([AZ]+)([AZ][az])/,'\1_\2'). gsub(/([az\d])([AZ])/,'\1_\2'). tr('-', '_'). gsub(/\s/, '_'). gsub(/__+/, '_'). downcase end # alias_method :underscore, :snakecase # TODO: Add *separators to #snakecase, like camelcase. end 

我想这样做:

 class String # \n returns the capture group of "n" index def snikize self.gsub(/::/, '/') .gsub(/([az\d])([AZ])/, "\1_\2") .downcase end # or def snikize self.gsub(/::/, '/') .gsub(/([az\d])([AZ])/) do "#{$1}_#{$2}" end .downcase end end 

String类的Monkey修补程序。 有两个或两个以上的字母大写的类。

如果您还有空位,也可以使用CamelCases的短string(如果您有一个字母小的起始字母,则不能正常工作):

 a = "Test String" a.gsub(' ', '').underscore => "test_string"