How to turn a string into CamelCase in Ruby
Here’s a function to turn any given string into a CamelCase “WikiWord” in Ruby:
def wikify(phrase)
phrase.gsub!(/^[a-z]|\s+[a-z]/) { |a| a.upcase }
phrase.gsub!(/\s/, '')
return phrase
end
Voila. This turns “my dog has fleas” into “MyDogHasFleas”.
Note: I’m sure there’s a way to fix this so that it’s just one regular expression? Feel free to chime in!
Posted: July 21st, 2007 by Neal Enssle
Tags: code, howto, programming, rails
6 Comments »
If you’re in Rails, you can take advantage of the Inflector class and do something like this:
>> phrase = ‘my Dog hAs FlEas’
=> “my Dog hAs FlEas”
>> phrase.downcase.gsub(/\s/, ‘_’).camelize
=> “MyDogHasFleas”
I only know this because the inflector’s “titleize” method is great if you want to “capitalize” multi-word phrases.
Oh, and I don’t think you even need the return statement.
I’m pretty sure Ruby methods automagically return the last thing that gets evaluated within.
def wikify(phrase)
phrase.downcase.gsub(/\b[a-z]/) { |a| a.upcase }.gsub(/\s/, ”)
end
This fails if the string is already in camel case. Also:
phrase.gsub!(/s/, ”)
would return nil if no substitutions were made to phrase. gsub would return the result of phrase post-gsub even if no changes were made.
I’m pretty sure I’ve got this, in case anyone cares:
self.gsub!(/\W+/, ‘ ‘) # all non-word chars to spaces
self.strip!
self.underscore.split.join(“_”).camelcase(:lower)
assuming that self is a String. Our implementation mixes this method in to String on application startup.
Hope this helps someone.
I always thought camelCase was lowercase for the first-most character. But upon further investigation, I see that is not AlwaysTheCase (LOL @ PascalCase).