mercredi 29 juillet 2015

Ruby Conditional Test

I can't make my code pass this test:

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

I don't see the flaw in my logic, though it may be very brute force and there may be a simpler way of passing the test:

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

Here's the test failure message:

Failures:

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

The additional code checking other conditions are for other tests that I already passed. Basically, now I'm checking a string with two words.

Please let me know how I can make the code pass the test. Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire