views:

1968

answers:

3

Is there any ready function which converts camel case Strings into underscore separated string? I want something like this

"CamelCaseString".to_undescore

to return "camel_case_string"

+7  A: 

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

class String
   def underscore(camel_cased_word)
     camel_cased_word.to_s.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
jrhicks
Exactly what I wanted! Thanks
Daniel Cukier
+2  A: 

Here's how Rails does it:

   def underscore(camel_cased_word)
     camel_cased_word.to_s.gsub(/::/, '/').
       gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
       gsub(/([a-z\d])([A-Z])/,'\1_\2').
       tr("-", "_").
       downcase
   end
Pesto
Better to have the operand as a method argument rather than to invade the core String class.
Pistos
A: 

One-liner Ruby implementation:

class String
   def to_underscore!
     self.gsub!(/(.)([A-Z])/,'\1_\2').downcase!
   end
   def to_underscore
     self = self.clone.to_underscore!
   end
end

So "SomeCamelCase".to_underscore # =>"some_camel_case"

kirushik
how are the other solutions not pure ruby?
jrhicks
Oh, sh...Thanks - I was more interested in writing than in reading. As a result - links on Rails made me think those other snippets to be Rails-specific.Changed answer...
kirushik