Converting string from snake_case to CamelCase in Ruby

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

    I got here looking for the inverse of your question, going from camel case to snake case. Use underscore for that (not decamelize):

    AppUser.name.underscore # => "app_user"

    or, if you already have a camel case string:

    "AppUser".underscore # => "app_user"

    or, if you want to get the table name, which is probably why you'd want the snake case:

    AppUser.name.tableize # => "app_users"

    0 讨论(0)
  • 2020-11-30 20:49

    I feel a little uneasy to add more answers here. Decided to go for the most readable and minimal pure ruby approach, disregarding the nice benchmark from @ulysse-bn. While :class mode is a copy of @user3869936, the :method mode I don't see in any other answer here.

      def snake_to_camel_case(str, mode: :class)
        case mode
        when :class
          str.split('_').map(&:capitalize).join
        when :method
          str.split('_').inject { |m, p| m + p.capitalize }
        else
          raise "unknown mode #{mode.inspect}"
        end
      end
    

    Result is:

    [28] pry(main)> snake_to_camel_case("asd_dsa_fds", mode: :class)
    => "AsdDsaFds"
    [29] pry(main)> snake_to_camel_case("asd_dsa_fds", mode: :method)
    => "asdDsaFds"
    
    0 讨论(0)
  • 2020-11-30 20:51

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

    0 讨论(0)
  • 2020-11-30 20:54

    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

    0 讨论(0)
提交回复
热议问题