我正在编写测试文件,但我无法通过第二次测试,这里:
def translate(word)
if word.start_with?('a','e','i','o','u')
word << "ay"
else
word << "bay"
end
end
Run Code Online (Sandbox Code Playgroud)
是start_with?正确的方法来完成这项工作吗?
describe "#translate" do
it "translates a word beginning with a vowel" do
s = translate("apple")
s.should == "appleay"
end
it "translates a word beginning with a consonant" do
s = translate("banana")
s.should == "ananabay"
end
it "translates a word beginning with two consonants" do
s = translate("cherry")
s.should == "errychay"
end
end
Run Code Online (Sandbox Code Playgroud)
编辑:我的解决方案不完整.我的代码只通过第一次测试,因为我能够将"ay"推到单词的末尾.通过第二次测试我错过的是删除第一个字母,如果它的辅音,在"香蕉"中是"b".
你也可以这样做:
word << %w(a e i o u).include?(word[0]) ? 'ay' : 'bay'
Run Code Online (Sandbox Code Playgroud)
在你的情况下使用正则表达式可能有点过分,但如果你想匹配更复杂的字符串,可能会很方便.
| 归档时间: |
|
| 查看次数: |
9196 次 |
| 最近记录: |