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!

2 Comments »

  1. 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.

    Comment by Jake — August 30, 2007 @ 6:56 am
  2. 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.

    Comment by Jake — August 30, 2007 @ 6:59 am

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2007 neal enssle. all rights reserved, yo.