4

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?

Elijah Murray
  • 2,132
  • 5
  • 30
  • 43

5 Answers5

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

Philip Hallstrom
  • 19,673
  • 2
  • 42
  • 46
  • Yeah, this works, but it seems like so much overkill. There's a `dasherize` method, as well as an `underscore` method. Is there anything similar that catches spaces? – Elijah Murray Jan 03 '14 at 22:57
  • I doubt it. Go look at the Rails source for these (and camelize) methods. It's the same thing, they just wrapped it up nice. – Philip Hallstrom Jan 03 '14 at 23:02
4

Using Rails' ActiveSupport, the following works for both cases:

"this is a sentence".underscore.parameterize("_").camelize(:lower)
# => "thisIsASentence"

"my-name".underscore.parameterize("_").camelize(:lower)
# => "myName"

the underscore converts any dashes, and the parameterize converts the spaces.

Mark Thomas
  • 37,131
  • 11
  • 74
  • 101
3

If you use ActiveSupport (for instance because of Rails or any other dependency), then have a look at the ActiveSupport::Inflector module. These methods are immediately available to you for any String.

'egg_and_hams'.classify # => "EggAndHam"
'posts'.classify        # => "Post"

Keep in mind that the standard separator in Ruby is the _, not the -. It means you probably need to replace it.

'my-name'.tr('-', '_').classify
 => "MyName" 
'my-name'.tr('-', '_').camelize(:lower)
 => "myName" 

Using ActiveSupport is just delegating the job. Keep in mind that, behind the scenes, these conversions in Ruby are very likely to be performed using regular expressions.

In fact, in Ruby regexp are cheap and very common.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
3
'this is a sentence'.split.map.with_index { |x,i| i == 0 ? x : x.capitalize  }.join # => "thisIsASentence"
bjhaid
  • 9,592
  • 2
  • 37
  • 47
0

You're looking for String#camelize

"test_string".camelize(:lower)           # => "testString"

If you're using other separators than underscore, use the gsub method to substitute other characters to underscores before camelizing.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Dries
  • 33
  • 5
  • 1
    No, I'm not. If you do `"test string".camelize(:lower)` it returns `"test string"` – Elijah Murray Jan 03 '14 at 22:56
  • If you're using other separaters than underscore, you can use the gsub method to substitute other characters to underscores before camelizing. – Dries Jan 03 '14 at 23:01