Converting Case to Underscore in Ruby

Asked

Viewed 79 times

3

There is a ready-to-use function that converts Strings to Camel case for strings separated by underscores?

I wish something like that:

"CamelCaseString".to_underscore      

return "camel_case_string".

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])/,'\1_\2').
    gsub(/([a-z\d])([A-Z])/,'\1_\2').
    tr("-", "_").
    downcase
  end
end

Ready:

"CamelCase".underscore
=> "camel_case"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.