user271586
user271586

Reputation:

English Sentence to Camel-cased method name

I had to convert a series of sentences into camel-cased method names. I ended writing something for it. I am still curious if there's something simpler for it.

Given the string a = "This is a test." output thisIsATest

I used for following:

a.downcase.gsub(/\s\w/){|b| b[-1,1].upcase }

Upvotes: 1

Views: 1001

Answers (4)

abhijit
abhijit

Reputation: 6723

You might try using the 'English' gem, available at http://english.rubyforge.org/

require 'english/case'

a = "This is a test."

a.camelcase().uncapitalize() # => 'thisIsATest

Upvotes: 0

Ragmaanir
Ragmaanir

Reputation: 2701

"Some string for you".gsub(/\s+/,'_').camelize(:lower) #=> "someStringForYou"
  1. gsub: Replace spaces by underscores
  2. camelize: java-like method camelcase

Upvotes: 1

Cimm
Cimm

Reputation: 4775

Not sure it's better as your solution but it should do the trick:

>> "This is a test.".titleize.split(" ").join.camelize(:lower)
=> "thisIsATest."
  • titleize: uppercase every first letter of each word
  • split(" ").join: create an array with each word and join to squeeze the spaces out
  • camelize(:lower): make the first letter lowercase

You can find some more fun functions in the Rails docs: http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html

Upvotes: 3

Sachin R
Sachin R

Reputation: 11876

"active_record".camelize(:lower)

output : "activeRecord"

use these

Upvotes: 2

Related Questions