Ruby条件测试

时间:2015-07-29 08:24:35

标签: ruby testing rspec

我无法让我的代码通过此测试:

it "translates two words" do
    s = translate("eat pie")
    s.should == "eatay iepay"
  end

我没有看到我的逻辑中的缺陷,虽然它可能是非常强力的,并且可能有一种更简单的方式通过测试:

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

这是测试失败消息:

故障:

 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)>'

检查其他条件的附加代码适用于我已经通过的其他测试。基本上,现在我正在检查一个包含两个单词的字符串。

请告诉我如何让代码通过测试。提前谢谢!

1 个答案:

答案 0 :(得分:5)

"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

如何使用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

或使用=~(正则表达式匹配):

irb(main):007:0> "e" =~ /[aeiou]/
=> 0