hackrnaut
hackrnaut

Reputation: 583

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!

Upvotes: 1

Views: 81

Answers (1)

falsetru
falsetru

Reputation: 368944

"a" || "e" || "i" || "o" || "u" is evaluated to "a" because "a" is truth value. (not a nil, not a 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

How about using Array#include? instead:

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

or using =~ (regular expression match):

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

Upvotes: 5

Related Questions