Ruby 我的代码的更好版本-错误的切片
我已经通过了测试,所以代码可以正常工作。它看起来确实有点难看,有点不可靠。有没有一种更适合Ruby的方法呢 这是我的解决方案Ruby 我的代码的更好版本-错误的切片,ruby,Ruby,我已经通过了测试,所以代码可以正常工作。它看起来确实有点难看,有点不可靠。有没有一种更适合Ruby的方法呢 这是我的解决方案 def start_of_word(word, x=1) @word = word[0,1+(x-1)] end 这些都是要通过的测试 describe "start_of_word" do it "returns the first letter" do start_of_word("hello", 1).should == "h"
def start_of_word(word, x=1)
@word = word[0,1+(x-1)]
end
这些都是要通过的测试
describe "start_of_word" do
it "returns the first letter" do
start_of_word("hello", 1).should == "h"
end
it "returns the first two letters" do
start_of_word("Bob", 2).should == "Bo"
end
it "returns the first several letters" do
s = "abcdefg"
start_of_word(s, 1).should == "a"
start_of_word(s, 2).should == "ab"
start_of_word(s, 3).should == "abc"
end
end
您已经重新实现了
slice
。它接受起始索引和长度:
def start_of_word(word, x=1)
@word = word.slice(1, x)
end
1+(x-1)
等于x
def start_of_word(word, x=1)
word[0, x]
end
通过测试不需要分配给
@word
。尝试完整性-在rails中,您只需执行word。首先(x)
它应该是word.slice(0,x)
,即可通过测试。