我的代码适用于一个单词,因此搜索器Proc工作正常。我试图通过将它们存储在数组中然后将每个单词传递给proc并将它们放在一起来使多个单词工作,但是当我测试诸如“eat pie”之类的东西时,它会返回它。你能告诉我我做错了什么吗?
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
答案 0 :(得分:3)
问题在于,您指的是x
中的searcher
,该x
对于传递到translate
的参数Proc
已关闭,当您真正想要做什么时是一次处理一个数组的每个元素。
我更改了代码的结构以便更容易推理 - 通过消除匿名#!/usr/bin/env ruby
def translate_word(x)
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
end
words = ARGV[0].split(' ').map { |word| translate_word(word) }.join(' ')
puts words
并使用惯用的Ruby映射来处理字符串 - 无论是一个还是多个单词。
chmod +x pig_latin
./pig_latin "eat pie"
./pig_latin "eat"
验证:
{{1}}