Converting string from snake_case to CamelCase in Ruby
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 have a string "app_user"
I want to convert that to model AppUser
).
If you're using Rails, String#camelize is what you're looking for.
"active_record".camelize # => "ActiveRecord"
"active_record".camelize(:lower) # => "activeRecord"
If you want to get an actual class, you should use String#constantize on top of that.
"app_user".camelize.constantize
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
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..