第三个elsif语句生成nil而不是所需的输出

时间:2016-02-17 18:19:20

标签: ruby testing

执行BDD教程和测试要求将单词开头有两个辅音的单词翻译成pig latin。这是第二个elsif陈述是我遇到麻烦的地方。代码如下:

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

我的问题是第三个条件。输出是零,而不是'#y;这就是我想要的。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

这是因为你的

lst = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y']]
result = []  # collect your products

# n sublists: iterate over all 'sub_lengthes'
for length in xrange(1, len(lst)+1):
    # iterate over all possible combinations of sublists
    for c in itertools.combinations(lst, length):
        # iterate over all products for each combination
        for res in itertools.product(*c):
            result.append(res)

print(result)

>>> result
# 3 + 3 + 2 = 8 singletons 
[('a',), ('b',), ('c',), (1,), (2,), (3,), ('x',), ('y',), 
# 3*3 + 3*2 + 3*2 = 21 pairs
('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3), 
('a', 'x'), ('a', 'y'), ('b', 'x'), ('b', 'y'), ('c', 'x'), ('c', 'y'),
(1, 'x'), (1, 'y'), (2, 'x'), (2, 'y'), (3, 'x'), (3, 'y'), 
# 3*3*2 = 18 triplets
('a', 1, 'x'), ('a', 1, 'y'), ('a', 2, 'x'), ('a', 2, 'y'), ('a', 3, 'x'), ('a', 3, 'y'), ('b', 1, 'x'), ('b', 1, 'y'), ('b', 2, 'x'), ('b', 2, 'y'), ('b', 3, 'x'), ('b', 3, 'y'), ('c', 1, 'x'), ('c', 1, 'y'), ('c', 2, 'x'), ('c', 2, 'y'), ('c', 3, 'x'), ('c', 3, 'y')]

不是完整的辅音列表,特别是它不包括consonant = ["z", "b", "t", "g", "h"] 的{​​{1}},即arg[0]。因此"cherry"既不满足"c"也不满足"cherry",也不满足三个vowel.include?(arg[0]) / consonant.include?(arg[0])条件中的任何一个,条件块返回if。< / p>

答案 1 :(得分:0)

您好像应该使用or代替and。有关Ruby中布尔运算符的更多信息,请查看here。另外,我建议你做一些重构:

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

请注意,include?方法会返回true的{​​{1}},因此您可以省略false。此外,Ruby会自动返回== true语句的最后一个字符串,因此您也可以省略它。