Converting camel case to underscore case in ruby

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

class String
  def underscore
    self.gsub(/::/, "https://stackoverflow.com/").
    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"

Leave a Comment