Converting string from snake_case to CamelCase in Ruby

前端 未结 10 1084
情书的邮戳
情书的邮戳 2020-11-30 19:57

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

10条回答
  •  遥遥无期
    2020-11-30 20:36

    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)

    x="this_should_be_camel_case"
    x.gsub(/(?:_|^)(\w)/){$1.upcase}
        #=> "ThisShouldBeCamelCase"
    

提交回复
热议问题