ruby-on-railsrubystringformattingcase-conversion

Converting camel case to underscore case in ruby


Is there any ready function which converts camel case Strings into underscore separated string?

I want something like this:

"CamelCaseString".to_underscore      

to return "camel_case_string".

...


Solution

  • Rails' ActiveSupport adds underscore to the String using the following:

    class String
      def underscore
        self.gsub(/::/, '/').
        gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
        gsub(/([a-z\d])([A-Z])/,'\1_\2').
        tr("-", "_").
        downcase
      end
    end
    

    Then you can do fun stuff:

    "CamelCase".underscore
    => "camel_case"