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: , , ,
6 Comments »

6 Comments on “How to turn a string into CamelCase in Ruby”

  1. 1 Jake said at 6:56 am on August 30th, 2007:

    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.

  2. 2 Jake said at 6:59 am on August 30th, 2007:

    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.

  3. 3 Joe said at 1:29 pm on October 4th, 2007:

    def wikify(phrase)
    phrase.downcase.gsub(/\b[a-z]/) { |a| a.upcase }.gsub(/\s/, ”)
    end

  4. 4 Rob said at 6:50 am on May 12th, 2008:

    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.

  5. 5 Rob said at 6:25 am on May 21st, 2008:

    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.

  6. 6 Mister Hectic said at 9:59 pm on September 17th, 2009:

    I always thought camelCase was lowercase for the first-most character. But upon further investigation, I see that is not AlwaysTheCase (LOL @ PascalCase).


Leave a Reply