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

我想要这样的东西:

"CamelCaseString".to_underscore      

返回“camel_case_string”。

...


当前回答

我想要这样:

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

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

其他回答

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

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

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

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"

我想要这样:

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

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

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

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

'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