Ruby regexp to turn snake_casing into PascalCasing?

I created a web framework that uses the following function:

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

To include directory names that are snake_casedor hyphen-casedin PascalCasedclass names for your project.

The problem is that the function removes only _and -not use the next letter. Using .capitalizeor .upcase, is there a way to make your names the snake/hyphen_/-casedcorrect class names PascalCased?

+3
source share
4 answers

This splits the _-circled string into an array; uppercase letters of each element and binds the array to a string:

def to_pascal_case(str)
  str.split(/-|_/).map(&:capitalize).join
end

p to_pascal_case("snake_cased") #=>"SnakeCased"

Your code does not work for several reasons:

  • capizing - - text.capitalize! text = text.capitalize.
  • capitalize upcase - , .
+4
gsub(/(?:^|[_-])([a-z])?/) { $1.upcase unless $1.nil? }
+5

Rails has a similar camelize method . It basically capitalizes every part of the line consisting of [a-z0-9]and removes everything else.

+2
source

You can probably play golf for something less, but:

txt = 'foo-bar_baz'
txt.gsub(/(?:^|[-_])([a-z])/) { |m| m.upcase }.gsub(/[-_]/, '') # FooBarBaz
+1
source

All Articles