在 ruby​​ 中将驼峰大小写转换为下划线大小写

发布于 2024-08-06 06:33:41 字数 168 浏览 4 评论 0原文

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

我想要这样的东西:

"CamelCaseString".to_underscore      

返回“camel_case_string”。

...

Is there any ready function which converts camel case Strings into underscore separated string?

I want something like this:

"CamelCaseString".to_underscore      

to return "camel_case_string".

...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

猫卆 2024-08-13 06:33:41

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"

Rails' ActiveSupport
adds underscore to the String using the following:

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

Then you can do fun stuff:

"CamelCase".underscore
=> "camel_case"
嗳卜坏 2024-08-13 06:33:41

您可以使用

"CamelCasedName".tableize.singularize

或仅使用

"CamelCasedName".underscore

两种方式都会产生“camel_cased_name”。您可以在此处查看更多详细信息。

您需要 active_support/inflector 才能正常工作(请参阅评论)。

You can use

"CamelCasedName".tableize.singularize

Or just

"CamelCasedName".underscore

Both options ways will yield "camel_cased_name". You can check more details it here.

You need to require active_support/inflector for it to work (see comments).

断桥再见 2024-08-13 06:33:41

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

One-liner Ruby implementation:

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

So "SomeCamelCase".to_underscore # =>"some_camel_case"

谁的新欢旧爱 2024-08-13 06:33:41

Rails 有一个名为“underscore”的内置方法,您可以将其用于此目的。

"CamelCaseString".underscore #=> "camel_case_string" 

“underscore”方法通常可以被视为“camelize”的逆方法

There is a Rails inbuilt method called 'underscore' that you can use for this purpose

"CamelCaseString".underscore #=> "camel_case_string" 

The 'underscore' method can typically be considered as inverse of 'camelize'

樱花落人离去 2024-08-13 06:33:41

如果有人寻找需要将下划线应用于带有空格的字符串并希望将它们转换为下划线的情况,您可以使用类似这样的东西

'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

In case someone looking for case when he need to apply underscore to string with spaces and want to convert them to underscores as well you can use something like this

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

Or just use .parameterize('_') but keep in mind that this one is deprecated

'your String will be converted To underscore'.parameterize('_')
#your_string_will_be_converted_to_underscore
番薯 2024-08-13 06:33:41

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

Here's how 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
人心善变 2024-08-13 06:33:41

当您还包含空格时,CamelCases 的短单行符(如果中间有一个带有小起始字母的单词,则无法正常工作):

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

编辑: 正如 @dft 所指出的,那么此方法不是一部分Ruby 和 Rails 的区别。

Short oneliner for CamelCases when you have spaces also included (doesn't work correctly if you have a word inbetween with small starting-letter):

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

EDIT: As pointed out by @dft then this method is not part of Ruby but Rails.

甜心小果奶 2024-08-13 06:33:41

查看来自 Ruby Facetssnakecase

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

"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

Check out snakecase from Ruby Facets

The following cases are handled, as seen below:

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

From: 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
月牙弯弯 2024-08-13 06:33:41

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

Receiver converted to snake case: http://rubydoc.info/gems/extlib/0.9.15/String#snake_case-instance_method

This is the Support library for DataMapper and 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"
最美的太阳 2024-08-13 06:33:41

我在 rake 任务中运行 "CamelCaseString".underscore 时遇到问题。这对我有帮助:

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

当然,您需要需要 ActiveSupport

I had trouble running "CamelCaseString".underscore in a rake task. This helped me:

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

Of course, you need to require ActiveSupport

傾旎 2024-08-13 06:33:41

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

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

有一个名为 lucky_case 的小型 ruby​​ gem,它允许您轻松地将字符串从 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

The ruby core itself has no support to convert a string from (upper) camel case to (also known as pascal case) to underscore (also known as snake case).

So you need either to make your own implementation or use an existing gem.

There is a small ruby gem called lucky_case which allows you to convert a string from any of the 10+ supported cases to another case easily:

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'

You can even monkey patch the String class if you want to:

require 'lucky_case/string'

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

Have a look at the offical repository for more examples and documentation:

https://github.com/magynhard/lucky_case

扎心 2024-08-13 06:33:41

我想要这样:

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

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

I would like this:

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

Monkey patch of String class. There are class that begin with two or more letters in uppercase.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文