hac*_*aut 1 ruby testing rspec
我不能让我的代码通过这个测试:
it "translates two words" do
s = translate("eat pie")
s.should == "eatay iepay"
end
Run Code Online (Sandbox Code Playgroud)
我没有看到我的逻辑中的缺陷,虽然它可能是非常强大的力量,并且可能有一种更简单的方式来通过测试:
def translate(string)
string_array = string.split
string_length = string_array.size
i=0
while i < string_length
word = string_array[i]
if word[0] == ("a" || "e" || "i" || "o" || "u")
word = word + "ay"
string_array[i] = word
elsif word[0] != ( "a" || "e" || "i" || "o" || "u" ) && word[1] != ( "a" || "e" || "i" || "o" || "u" )
word_length = word.length-1
word = word[2..word_length]+word[0]+word[1]+"ay"
string_array[i] = word
elsif word[0] != ( "a" || "e" || "i" || "o" || "u" )
word_length = word.length-1
word = word[1..word_length]+word[0]+"ay"
string_array[i] = word
end
i += 1
end
return string_array.join(" ")
end
Run Code Online (Sandbox Code Playgroud)
这是测试失败消息:
失败:
1) #translate translates two words
Failure/Error: s.should == "eatay iepay"
expected: "eatay iepay"
got: "ateay epiay" (using ==)
# ./04_pig_latin/pig_latin_spec.rb:41:in `block (2 levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)
检查其他条件的附加代码用于我已经通过的其他测试.基本上,现在我正在检查一个包含两个单词的字符串.
请让我知道如何让代码通过测试.先感谢您!
"a" || "e" || "i" || "o" || "u"被评估是"a"因为"a"是真值.(不是nil,不是false):
irb(main):001:0> ("a" || "e" || "i" || "o" || "u")
=> "a"
irb(main):002:0> "a" == ("a" || "e" || "i" || "o" || "u")
=> true
irb(main):003:0> "e" == ("a" || "e" || "i" || "o" || "u")
=> false
Run Code Online (Sandbox Code Playgroud)
如何使用Array#include?代替:
irb(main):001:0> %w{a e i o u}.include? "a"
=> true
irb(main):002:0> %w{a e i o u}.include? "e"
=> true
Run Code Online (Sandbox Code Playgroud)
或使用=~(正则表达式匹配):
irb(main):007:0> "e" =~ /[aeiou]/
=> 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |