rubyregex

Convert camelCase to dash-case (hypens) in pure ruby


There are plenty of posts about the opposite way.

But how to I convert camelCase to camel-case in ruby? My regex-game is pretty low ... here is it the other way around:

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

Solution

  • ActiveRecord already has it:

    gem install i18n activesupport-inflector
    

    then

    require 'active_support/inflector'
    "myHTMLComponent".underscore.dasherize
    # => "my-html-component"
    

    You can see the implementation here (with acronym_underscore_regex here).

    If you don't want to worry about corner cases like acronyms, this should suffice:

    "myCamelCase".gsub(/[[:upper:]]/) { "-#{$&.downcase}" }
    # => "my-camel-case"