2014-06-13 41 views
0

我一直在试图弄清楚如何满足我正在做的教程的一些条件。麻烦转换字符串为驼峰案例

我有以下的测试规范工作从:

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 

我设法让前两个条件与下面的代码的工作,但我已经尝试了一堆不同的东西,以获得加入和沮丧与首都条件下工作没有成功。

class String 
    def camel_case 
    self.downcase 
    end 
end 

我一直在想,使用.split然后.join方法将工作,但它不会。

+0

您可以添加“.split then .join方法”吗? – Stefan

+2

难道你不能使用[camelize](http://www.apidock.com/rails/String/camelize) –

+0

使用split来给自己一个单词的数组,然后可能每个单词都有索引来单独操作数组中的每个单词?每个索引的重点在于,您可以识别第一个单词(以免改写它的第一个字母)...或者可以使用map来改写数组中每个单词的第一个字母,然后使用join,然后使用join,然后使用第一个字母... – user3334690

回答

1

问题是你实际上没有做任何骆驼化。你的camel_case方法所做的唯一一件事就是使得这个短语的所有字母......呃...下来。然后 splitjoin是正确的事情。

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 
+0

不要忘记加入后的第一个字母,否则它将WillBeLikeThis而不是这个... – user3334690

1

而不是使用camelize或camelcase。

相关问题