Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regexp to turn snake_casing to PascalCasing?

I've created a web framework that uses the following function:

def to_class(text)
    text.capitalize
    text.gsub(/(_|-)/, '')
end

To turn directory names that are snake_cased or hyphen-cased into PascalCased class names for your project.

Problem is, the function only removed _ and -, and doesn't capitalize the next letter. Using .capitalize, or .upcase, is there a way to achieve making your snake/hyphen_/-cased names into proper PascalCased class names?

like image 605
beakr Avatar asked Mar 27 '26 19:03

beakr


1 Answers

gsub(/(?:^|[_-])([a-z])?/) { $1.upcase unless $1.nil? }
like image 115
aztaroth Avatar answered Mar 30 '26 12:03

aztaroth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!