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 »