Converting string from snake_case to CamelCase in Ruby

前端 未结 10 1121
情书的邮戳
情书的邮戳 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:34

    Benchmark for pure Ruby solutions

    I took every possibilities I had in mind to do it with pure ruby code, here they are :

    • capitalize and gsub

      'app_user'.capitalize.gsub(/_(\w)/){$1.upcase}
      
    • split and map using & shorthand (thanks to user3869936’s answer)

      'app_user'.split('_').map(&:capitalize).join
      
    • split and map (thanks to Mr. Black’s answer)

      'app_user'.split('_').map{|e| e.capitalize}.join
      

    And here is the Benchmark for all of these, we can see that gsub is quite bad for this. I used 126 080 words.

                                  user     system      total        real
    capitalize and gsub  :      0.360000   0.000000   0.360000 (  0.357472)
    split and map, with &:      0.190000   0.000000   0.190000 (  0.189493)
    split and map        :      0.170000   0.000000   0.170000 (  0.171859)
    

提交回复
热议问题