Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Sentence to Camelcase in Ruby [duplicate]

This seems like it would be ridiculously easy, but I can't find a method anywhere, to convert a sentence string/hyphenated string to camelcase.

Ex:
'this is a sentence' => 'thisIsASentence'
'my-name' => 'myName'

Seems overkill to use regex. What's the best way?

like image 713
Elijah Murray Avatar asked Dec 01 '22 17:12

Elijah Murray


1 Answers

> s = 'this is a sentence'
 => "this is a sentence"
> s.gsub(/\s(.)/) {|e| $1.upcase}
 => "thisIsASentence"

You'd need to tweak that regexp to match on dashes in additions to spaces, but that's easy.

Pretty sure there's a regexp way to do it as well without needing to use the block form, but I didn't look it up.

like image 63
Philip Hallstrom Avatar answered Dec 15 '22 00:12

Philip Hallstrom