Ruby regexp to turn snake_casing to PascalCasing?
-
12-12-2019 - |
Question
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?
Solution
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!
ortext = text.capitalize
. - But the
capitalize
method justupcase
s the first letter of the string, not the first letter of every word.
OTHER TIPS
gsub(/(?:^|[_-])([a-z])?/) { $1.upcase unless $1.nil? }
Rails has a similar method called camelize. It basically capitalizes every part of the string consisting of [a-z0-9]
and removes everything else.
You can probably golf it down to something smaller, but:
txt = 'foo-bar_baz'
txt.gsub(/(?:^|[-_])([a-z])/) { |m| m.upcase }.gsub(/[-_]/, '') # FooBarBaz