Thursday, February 3, 2011

How to turn a string into CamelCase in Ruby


Below are the few tricks to capitalize only the first letter of each word of a multi word string.
def wikify(phrase)
phrase.gsub!(/^[a-z]|\s+[a-z]/) { |a| a.upcase }
phrase.gsub!(/\s/, '')
return phrase
end
This turns “my dog has fleas” into “MyDogHasFleas”.


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.


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

  'some string here'.gsub(/\b\w/){$&.upcase}
>> Some String Here

No comments:

Post a Comment