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

Piper

New Member
#1
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:
Mã:
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
 

Admin

Administrator
Thành viên BQT
#2
ActiveRecord already has it:
Mã:
gem install i18n activesupport-inflector
then
Mã:
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:

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

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top