Converting string from snake_case to CamelCase in Ruby

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

    Extend String to Add Camelize

    In pure Ruby you could extend the string class using the exact same code from Rails .camelize

    class String
      def camelize(uppercase_first_letter = true)
        string = self
        if uppercase_first_letter
          string = string.sub(/^[a-z\d]*/) { |match| match.capitalize }
        else
          string = string.sub(/^(?:(?=\b|[A-Z_])|\w)/) { |match| match.downcase }
        end
        string.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }.gsub("/", "::")
      end
    end
    

提交回复
热议问题