在Ruby中将字符串从snake_case转换为CamelCase
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9524457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting string from snake_case to CamelCase in Ruby
提问by Lohith MV
I am trying to convert a name from snake case to camel case. Are there any built-in methods?
我正在尝试将名称从蛇形案例转换为驼色案例。有没有内置的方法?
Eg: "app_user"to "AppUser"
例如:"app_user"到"AppUser"
(I have a string "app_user"I want to convert that to model AppUser).
(我有一个字符串,"app_user"我想将其转换为 model AppUser)。
回答by Sergio Tulentsev
If you're using Rails, String#camelizeis what you're looking for.
如果您使用 Rails,那么String#camelize就是您要找的。
"active_record".camelize # => "ActiveRecord"
"active_record".camelize(:lower) # => "activeRecord"
If you want to get an actual class, you should use String#constantizeon top of that.
如果你想获得一个实际的类,你应该在它之上使用String#constantize。
"app_user".camelize.constantize
回答by user3869936
How about this one?
这个怎么样?
"hello_world".split('_').collect(&:capitalize).join #=> "HelloWorld"
Found in the comments here: Classify a Ruby string
在此处的评论中找到: Classify a Ruby string
See comment by Wayne Conrad
见注释韦恩·康拉德
回答by Harish Shetty
If you use Rails, Use classify. It handles edge cases well.
如果您使用 Rails,请使用classify. 它可以很好地处理边缘情况。
"app_user".classify # => AppUser
"user_links".classify # => UserLink
Note:
笔记:
This answer is specific to the description given in the question(it is not specific to the question title). If one is trying to convert a string to camel-case they should use Sergio's answer. The questioner states that he wants to convert app_userto AppUser(not App_user), hence this answer..
此答案特定于问题中给出的描述(并非特定于问题标题)。如果有人试图将字符串转换为驼峰式大小写,他们应该使用Sergio的答案。提问者说他想转换app_user为AppUser(not App_user),因此这个答案..
回答by Mr. Black
Source: http://rubydoc.info/gems/extlib/0.9.15/String#camel_case-instance_method
来源:http: //rubydoc.info/gems/extlib/0.9.15/String#camel_case-instance_method
For learning purpose:
学习目的:
class String
def camel_case
return self if self !~ /_/ && self =~ /[A-Z]+.*/
split('_').map{|e| e.capitalize}.join
end
end
"foo_bar".camel_case #=> "FooBar"
And for the lowerCase variant:
对于小写变体:
class String
def camel_case_lower
self.split('_').inject([]){ |buffer,e| buffer.push(buffer.empty? ? e : e.capitalize) }.join
end
end
"foo_bar".camel_case_lower #=> "fooBar"
回答by Ulysse BN
Benchmark for pure Ruby solutions
纯 Ruby 解决方案的基准
I took every possibilities I had in mind to do it with pure ruby code, here they are :
我想尽一切办法用纯 ruby 代码来做这件事,它们是:
capitalize and gsub
'app_user'.capitalize.gsub(/_(\w)/){.upcase}split and map using
&shorthand (thanks to user3869936's answer)'app_user'.split('_').map(&:capitalize).joinsplit and map (thanks to Mr. Black's answer)
'app_user'.split('_').map{|e| e.capitalize}.join
大写和 gsub
'app_user'.capitalize.gsub(/_(\w)/){.upcase}使用
&速记拆分和映射(感谢 user3869936 的回答)'app_user'.split('_').map(&:capitalize).join拆分和映射(感谢布莱克先生的回答)
'app_user'.split('_').map{|e| e.capitalize}.join
And here is the Benchmark for all of these, we can see that gsub is quite bad for this. I used 126 080 words.
这是所有这些的基准,我们可以看到 gsub 对此非常不利。我用了 126 080 个单词。
user system total real
capitalize and gsub : 0.360000 0.000000 0.360000 ( 0.357472)
split and map, with &: 0.190000 0.000000 0.190000 ( 0.189493)
split and map : 0.170000 0.000000 0.170000 ( 0.171859)
回答by mike
I got here looking for the inverse of your question, going from camel case to snake case. Use underscorefor that (not decamelize):
我来这里是为了寻找与您的问题相反的问题,从骆驼案例到蛇案例。使用下划线(不是 deamelize):
AppUser.name.underscore # => "app_user"
AppUser.name.underscore # => "app_user"
or, if you already have a camel case string:
或者,如果您已经有一个驼峰式字符串:
"AppUser".underscore # => "app_user"
"AppUser".underscore # => "app_user"
or, if you want to get the table name, which is probably why you'd want the snake case:
或者,如果您想获得表名,这可能就是您想要蛇形案例的原因:
AppUser.name.tableize # => "app_users"
AppUser.name.tableize # => "app_users"
回答by akostadinov
I feel a little uneasy to add more answers here. Decided to go for the most readable and minimal pure ruby approach, disregarding the nice benchmark from @ulysse-bn. While :classmode is a copy of @user3869936, the :methodmode I don't see in any other answer here.
我觉得在这里添加更多答案有点不安。决定采用最具可读性和最小的纯 ruby 方法,无视@ulysse-bn 的良好基准。虽然:class模式是@user3869936 的副本,但:method我在此处的任何其他答案中都看不到该模式。
def snake_to_camel_case(str, mode: :class)
case mode
when :class
str.split('_').map(&:capitalize).join
when :method
str.split('_').inject { |m, p| m + p.capitalize }
else
raise "unknown mode #{mode.inspect}"
end
end
Result is:
结果是:
[28] pry(main)> snake_to_camel_case("asd_dsa_fds", mode: :class)
=> "AsdDsaFds"
[29] pry(main)> snake_to_camel_case("asd_dsa_fds", mode: :method)
=> "asdDsaFds"
回答by Cameron Lowell Palmer
Extend String to Add Camelize
扩展字符串以添加 Camelize
In pure Ruby you could extend the string class using the exact same code from Rails .camelize
在纯 Ruby 中,您可以使用与 Rails 完全相同的代码扩展字符串类 .camelize
class String
def camelize(uppercase_first_letter = true)
string = self
if uppercase_first_letter
string = string.sub(/^[a-z\d]*/) { |match| match.capitalize }
else
string = string.sub(/^(?:(?=\b|[A-Z_])|\w)/) { |match| match.downcase }
end
string.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{}#{.capitalize}" }.gsub("/", "::")
end
end
回答by masukomi
Most of the other methods listed here are Rails specific. If you want do do this with pure Ruby, the following is the most concise way I've come up with (thanks to @ulysse-bn for the suggested improvement)
此处列出的大多数其他方法都是特定于 Rails 的。如果你想用纯 Ruby 来做这件事,下面是我想出的最简洁的方法(感谢@ulysse-bn 提出的改进建议)
x="this_should_be_camel_case"
x.gsub(/(?:_|^)(\w)/){.upcase}
#=> "ThisShouldBeCamelCase"

