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

Viewed 1301

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
2 Answers

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"

here it is:

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

not that complicated after all ...

Related