Kevin Bellinger
Kevin Bellinger

Reputation: 15

Having Trouble converting string to camel case

I´ve been trying to figure out how to satisfy some conditions for a tutorial I am doing.

I have the following test spec to work from:

describe "String" do
  describe "camel_case" do
    it "leaves first word lowercase" do
      "test".camel_case.should eq("test")
    end
    it "should lowercase first letter if it isn't" do
      "Test".camel_case.should eq("test")
    end
    it "should combine words using camel case" do
      "This is a test".camel_case.should eq("thisIsATest")
    end
    it "should downcase words with capitals" do
      "MUST dOWNCASE words".camel_case.should eq("mustDowncaseWords")
    end
  end
end

I have managed to get the first two conditions working with the code below, but I have tried a bunch of different things to get the join and downcast with capitals conditions to work without success.

class String
  def camel_case
    self.downcase 
  end
end

I had been thinking that using a .split then .join method would work, but it does not.

Upvotes: 0

Views: 156

Answers (2)

Marlin Pierce
Marlin Pierce

Reputation: 10099

Instead of downcase use camelize or camelcase.

Upvotes: 1

twonegatives
twonegatives

Reputation: 3458

The problem is that you actually do not do any camelizing. The only thing your camel_case method does is makes all the letters of the phrase... eh... down-cased. split and join afterwards are the right things to do though.

class String
  def camel_case
    downcased = self.downcase # here you only downcased your input
    array_of_words = downcased.split
    # now you should make the first letter of each word upper-cased
    # ...
    words_with_first_letter_capitalized.join
  end
end

Upvotes: 1

Related Questions