Reputation: 69
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.
Upvotes: 0
Views: 39
Reputation: 13487
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.
Upvotes: 0
Reputation: 168269
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
.
Upvotes: 1