Converting camel case to underscore in Ruby

3

Is there a ready-made function that converts strings into camel cases for strings separated by underscores?

I would like something like this:

"CamelCaseString".to_underscore      

return "camel_case_string" .

    
asked by anonymous 10.08.2014 / 04:34

1 answer

5

Rails' ActiveSupport adds underscore to the String class using this code:

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

Ready:

"CamelCase".underscore
=> "camel_case"
    
10.08.2014 / 04:35