我的代码适用于一个单词,因此搜索器 Proc 工作正常。我试图通过将它们存储在一个数组中然后将每个单词传递给 proc 并将它们放在一起来使其适用于多个单词,但是当我测试诸如“吃派”之类的东西时,它会返回这个。你能告诉我我做错了什么吗?
Failures:
1) translate translates two words
Failure/Error: s.should == "eatay iepay"
expected: "eatay iepay"
got: "eat pieay eat pieayay" (using ==)
# ./04_pig_latin/pig_latin_spec.rb:41:in `block (2 levels) in <top (required)>'
这是我的代码:
def translate(x)
array = x.split(' ')
searcher = Proc.new{
if x.index(/[aeiou]/) == 0
x = x + "ay"
elsif x[0..1] == "qu"
first = x.chr
x.reverse!.chop!.reverse!
second = x.chr
x.reverse!.chop!.reverse!
x = x + first + second + "ay"
elsif x.index(/[aeiou]/) == 1
first = x.chr
x.reverse!.chop!.reverse!
x = x + first + "ay"
elsif x[1..2] == "qu"
first = x.chr
x.reverse!.chop!.reverse!
second = x.chr
x.reverse!.chop!.reverse!
third = x.chr
x.reverse!.chop!.reverse!
x = x + first + second + third +"ay"
elsif x.index(/[aeiou]/) == 2
first = x.chr.chr
x.reverse!.chop!.reverse!
second = x.chr
x.reverse!.chop!.reverse!
x = x + first + second + "ay"
elsif x.index(/[aeiou]/) == 3
first = x.chr
x.reverse!.chop!.reverse!
second = x.chr
x.reverse!.chop!.reverse!
third = x.chr
x.reverse!.chop!.reverse!
x = x + first + second + third +"ay"
else
x
end
}
if array.count == 1
searcher.call
return x
else
return array.collect(&searcher).join(' ')
end
end