Converting string from snake_case to CamelCase in Ruby

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

提交回复
热议问题