将驼峰案例转换为ruby中的下划线案例

时间:2009-10-02 14:36:59

标签: ruby-on-rails ruby string formatting case-conversion

是否有任何现成的函数可以将驼峰字符串转换为下划线字符串?

我想要这样的事情:

"CamelCaseString".to_underscore      

返回“camel_case_string”。

...

11 个答案:

答案 0 :(得分:336)

Rails' ActiveSupport 使用以下内容向String添加下划线:

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"

答案 1 :(得分:75)

您可以使用

"CamelCasedName".tableize.singularize

或者只是

"CamelCasedName".underscore

两种选择方式都会产生"camel_cased_name"。您可以查看更多详细信息here

答案 2 :(得分:53)

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

答案 3 :(得分:26)

有一个称为“下划线”的Rails内置方法可用于此目的

"CamelCaseString".underscore #=> "camel_case_string" 

'下划线'方法通常可以被视为'camelize'的反转

答案 4 :(得分:18)

以下是Rails does it

的方式
   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

答案 5 :(得分:7)

接收者转换为蛇案: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"

答案 6 :(得分:7)

Ruby Facets

查看 snakecase

处理以下案件,如下所示:

"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

答案 7 :(得分:5)

如果您还包含空格,那么CamelCases的短线程(如果您的中间有一个小字母,则无法正常工作):

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

  => "test_string"

答案 8 :(得分:2)

ruby​​核心本身不支持将字符串从(上)驼峰大小写(也称为pascal大小写)转换为下划线(也称为蛇形大小写)。

因此,您需要自己实施或使用现有的gem。

有一个名为 lucky_case 的小红宝石,可让您轻松地将字符串从支持的10多种情况中的任何一种转换为另一种情况:

require 'lucky_case'

# convert to snake case string
LuckyCase.snake_case('CamelCaseString')      # => 'camel_case_string'
# or the opposite way
LuckyCase.pascal_case('camel_case_string')   # => 'CamelCaseString'

如果愿意,您甚至可以猴子修补String类:

require 'lucky_case/string'

'CamelCaseString'.snake_case  # => 'camel_case_string'
'CamelCaseString'.snake_case! # => 'camel_case_string' and overwriting original

有关更多示例和文档,请查看官方存储库:

https://github.com/magynhard/lucky_case

答案 9 :(得分:1)

我想这样:

class String

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

  # or

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

end

String类的猴子补丁。有一个类以两个或多个大写字母开头。

答案 10 :(得分:1)

如果有人在寻找需要将下划线应用于带空格的字符串并将其转换为下划线的情况时,也可以使用类似这样的

'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