0

Performing a BDD tutorial and the test requires that a word that has two consonants at the beginning of a word be translated into pig latin. It is the the second elsif statement is where I am having trouble. The code is as follows:

def translate(arg)

    vowel = ["a", "e", "i", "o", "u"]
    vowel_word = "ay"

    consonant = ["z", "b", "t", "g", "h"]
    consonant_word = "ay"

    if vowel.include?(arg[0]) == true
        return arg + vowel_word
    elsif consonant.include?(arg[0]) == true
        foo = arg[1,6]
        return foo + arg[0] + consonant_word
    elsif (consonant.include?(arg[0]) == true) and (consonant.include?(arg[1]) == true)
        foo = arg[2, 5]
        return foo + arg[0] + arg[1] + consonant_word
    end
end

translate("apple")
translate("banana")
translate("cherry")

My problem is with the third condition. The output is nil, not 'errychay' which is what I want. Any help will be appreciated.

0

2 Answers 2

1

It is because your

consonant = ["z", "b", "t", "g", "h"]

is not a full consonant list, particularly it does not include the arg[0] of "cherry", which is "c". So "cherry" satisfies neither vowel.include?(arg[0]) nor consonant.include?(arg[0]), nor any of the three if/elsif conditions, and the condition block returns nil.

0
0

It seems like you should use or instead of and. More about boolean operators in Ruby you can look here. Also, i advise you to do some refactoring:

def translate(arg)
  vowel = ["a", "e", "i", "o", "u"]
  vowel_word = "ay"
  consonant = ["z", "b", "t", "g", "h"]
  consonant_word = "ay"

  if vowel.include?(arg[0])
    arg + vowel_word
  elsif consonant.include?(arg[0])
    foo = arg[1,6]
    foo + arg[0] + consonant_word
  elsif consonant.include?(arg[0]) || consonant.include?(arg[1])
    foo = arg[2, 5]
    foo + arg[0] + arg[1] + consonant_word
  end
end

Note, that include? method returns true of false, so you may omit == true. Also, Ruby automatically returns last string of if..else statement, so you can omit it too.

4
  • Awesome thank you very much, this worked like a charm.
    – JCD
    Feb 17, 2016 at 18:43
  • 1
    There is nothing wrong about this post, but it should be a comment to the question rather than an answer.
    – sawa
    Feb 17, 2016 at 18:46
  • Why? Question was The output is nil, not 'errychay' which is what I want. I answered on question, and gave link for more details about boolean operators.
    – Ilya
    Feb 17, 2016 at 18:50
  • @sawa it answered my question and got my code to behave the way I intended
    – JCD
    Feb 18, 2016 at 3:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.