在Ruby中将字符串从snake_case转换为CamelCase [英] Converting string from snake_case to CamelCase in Ruby

查看:56
本文介绍了在Ruby中将字符串从snake_case转换为CamelCase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将名称从蛇形案例转换为驼色案例.是否有任何内置方法?

I am trying to convert a name from snake case to camel case. Are there any built-in methods?

例如:"app_user""AppUser"

(我有一个字符串 "app_user" 我想将其转换为模型 AppUser).

(I have a string "app_user" I want to convert that to model AppUser).

推荐答案

如果您使用 Rails,String#camelize 正是您要找的.

If you're using Rails, String#camelize is what you're looking for.

  "active_record".camelize                # => "ActiveRecord"
  "active_record".camelize(:lower)        # => "activeRecord"

如果你想得到一个实际的类,你应该使用 String#在此基础上保持不变.

If you want to get an actual class, you should use String#constantize on top of that.

"app_user".camelize.constantize

这篇关于在Ruby中将字符串从snake_case转换为CamelCase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆