我正在努力解决这个问题。
将名为 add_index 的方法添加到 Array 类。该方法应获取元素位置的索引值并将其添加到相同位置的字符串中。
提示:each_with_index 方法应该可以帮助您解决这个问题。尝试自己在 Ruby Docs 中找到 each_with_index 方法,并了解它是如何使用的。
这是我当前的代码: **我不是在创建完整的类或使用 self,我只是在测试 self 对变量 a 的作用。在测试中,self 是通过“这是一个测试”。
new-host:~$ irb
2.0.0p247 :001 > a = "This is a test"
=> "This is a test"
2.0.0p247 :002 > a.split.join.downcase
=> "thisisatest"
2.0.0p247 :003 > a.split
=> ["This", "is", "a", "test"]
#Should I do something with the array first? I could pass them into a code block to call the .capitalize method on them...with this in mind I am not sure how to skp the [0] of the array.
2.0.0p247 :004 > a.split.join.downcase[0..3]
=> "this"
2.0.0p247 :005 > a.split.join.downcase.capitalize
=> "Thisisatest"
最终我需要“这是一个测试”看起来像“thisIsATest”。我一直试图弄清楚这一点。如果有人能提供一些见解,我将不胜感激。谢谢!
我的一个想法是做这样的事情:
a.split.each do |num| num.to_s.downcase
2.0.0p247 :010?> end
#I know this isn't right but from the syntax I know I think doing something like this is a step in the right direction.
“这是一个测试”是通过测试运行的内容:
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
end
end
我为我的方法排除了类 String 和 def camel_case。我只是想测试我的方法的代码块。