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

9 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).

  7. 7 Justin Baker said at 9:57 am on August 13th, 2010:

    @jake Indeed, no return is needed. It is implicit.

  8. 8 roger said at 8:22 pm on April 14th, 2011:

    def self.camelcase(phrase)
    (‘_’ + phrase).gsub(/_([a-z])/){|b| b[1..1].upcase}
    end

    works for me…though probably not the best.

  9. 9 ema said at 9:14 am on July 6th, 2011:

    gems “string_utils”!!!! has all this


Leave a Reply