Converting camel case to underscore case in ruby Converting camel case to underscore case in ruby ruby ruby

Converting camel case to underscore case in ruby


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  endend

Then you can do fun stuff:

"CamelCase".underscore=> "camel_case"


You can use

"CamelCasedName".tableize.singularize

Or just

"CamelCasedName".underscore

Both options ways will yield "camel_cased_name". You can check more details it here.


One-liner Ruby implementation:

class String   # ruby mutation methods have the expectation to return self if a mutation occurred, nil otherwise. (see http://www.ruby-doc.org/core-1.9.3/String.html#method-i-gsub-21)   def to_underscore!     gsub!(/(.)([A-Z])/,'\1_\2')     downcase!   end   def to_underscore     dup.tap { |s| s.to_underscore! }   endend

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