I am trying to convert a name from snake case to camel case. Are there any built-in methods?
Eg: \"app_user\"
to \"AppUser\"
(I hav
I got here looking for the inverse of your question, going from camel case to snake case. Use underscore for that (not decamelize):
AppUser.name.underscore # => "app_user"
or, if you already have a camel case string:
"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"
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 :class
mode is a copy of @user3869936, the :method
mode I don't see in any other answer here.
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"
If you use Rails, Use classify
. It handles edge cases well.
"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_user
to AppUser
(not App_user
), hence this answer..
How about this one?
"hello_world".split('_').collect(&:capitalize).join #=> "HelloWorld"
Found in the comments here: Classify a Ruby string
See comment by Wayne Conrad