Ruby regexp to turn snake_casing to PascalCasing?

295 views Asked by At

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?

4

There are 4 answers

1
steenslag On BEST ANSWER

This splits the _-cased string into an array; capitalizes every member and glues the array back 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:

  • The resulting object of the capitalize method is discarded - you should do something like text.capitalize! or text = text.capitalize.
  • But the capitalize method just upcases the first letter of the string, not the first letter of every word.
0
x1a4 On

You can probably golf it down to something smaller, but:

txt = 'foo-bar_baz'
txt.gsub(/(?:^|[-_])([a-z])/) { |m| m.upcase }.gsub(/[-_]/, '') # FooBarBaz
0
Holger Just On

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

1
aztaroth On
gsub(/(?:^|[_-])([a-z])?/) { $1.upcase unless $1.nil? }