Lohith MV Lohith MV - 6 months ago 128
Ruby Question

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
).

Answer

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