我想把一个字符串翻译成猪拉丁语。规则如下:
'a'
,'e'
,'i'
,'o'
或'u'
以外的字母开头)开头,那么字母转移到了单词的末尾。'ay'
。我设法提出了这个方法:
def translate(word)
if word.size <= 2
word
elsif
word.size > 2
!word.start_with?('a', 'e', 'i', 'o', 'u')
x = word.reverse.chop.reverse
x.insert(-1, word[0])
x << "ay"
else
word << "ay"
end
end
但是,我的测试没有通过某些字符串,
Test Passed: Value == "c"
Test Passed: Value == "pklqfay"
Test Passed: Value == "yykay"
Test Passed: Value == "fqhzcbjay"
Test Passed: Value == "ndnrzzrhgtay"
Test Passed: Value == "dsvjray"
Test Passed: Value == "qnrgdfay"
Test Passed: Value == "npfay"
Test Passed: Value == "ldyuqpewypay"
Test Passed: Value == "arqokudmuxay"
Test Passed: Value == "spvhxay"
Test Passed: Value == "firvmanxay"
Expected: 'aeijezpbay' - Expected: "aeijezpbay", instead got: "eijezpbaay"
Expected: 'etafhuay' - Expected: "etafhuay", instead got: "tafhueay"
这些测试通过:
Test.assert_equals(translate("billy"),"illybay","Expected: 'illybay'")
Test.assert_equals(translate("emily"),"emilyay","Expected: 'emilyay'")
我不确定为什么。
答案 0 :(得分:2)
你的代码失败了,因为它没有真正评估单词是否以常量开头,你只是检查它但却什么都不做,它只是一个孤立的行:
!word.start_with?('a', 'e', 'i', 'o', 'u')
尝试在if
条件中包含 行,如下所示:
def translate(word)
if word.size <= 2
word
else
if !word.start_with?('a', 'e', 'i', 'o', 'u')
x = word.reverse.chop.reverse
x.insert(-1, word[0])
x << "ay"
else
word << "ay"
end
end
end
另请注意,我删除了if word.size > 2
,因为您已经在检查word.size <= 2
,所以没有必要,因此除此之外的任何内容都是> 2
。
答案 1 :(得分:2)
如果word
的长度更大或等于2返回单词,如果没有,则执行start_with
步骤,但是else
语句何时起作用?
尝试将长度验证修改为小于2,然后检查单词&#34; start_with&#34;一个元音,只返回单词加ay
,如果没有,则第一个字符旋转步骤然后添加ay
部分,如:
def translate(word)
if word.size < 2
word
elsif word.start_with?('a', 'e', 'i', 'o', 'u')
word << "ay"
else
x = word.reverse.chop.reverse
x.insert(-1, word[0])
x << "ay"
end
end