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

我想要这样的东西:

"CamelCaseString".to_underscore      

返回“camel_case_string”。

...


当前回答

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

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

当然,您需要使用ActiveSupport

其他回答

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

"CamelCaseString".underscore #=> "camel_case_string" 

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

当你有空格的时候,camelcase的简短的一行程序也包括在内(如果你有一个小的开头字母之间的单词,就不能正常工作):

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

编辑:正如@dft指出的那样,这个方法不是Ruby的一部分,而是Rails的一部分。

下面是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

我想要这样:

class String

  # \n returns the capture group of "n" index
  def snakize
    self.gsub(/::/, '/')
    .gsub(/([a-z\d])([A-Z])/, "\1_\2")
    .downcase
  end

  # or

  def snakize
    self.gsub(/::/, '/')
    .gsub(/([a-z\d])([A-Z])/) do
      "#{$1}_#{$2}"
    end
    .downcase
  end

end

猴子补丁的字符串类。有些类以两个或多个大写字母开头。

看看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(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
    gsub(/([a-z\d])([A-Z])/,'\1_\2').
    tr('-', '_').
    gsub(/\s/, '_').
    gsub(/__+/, '_').
    downcase
  end

  #
  alias_method :underscore, :snakecase

  # TODO: Add *separators to #snakecase, like camelcase.

end