2

我的代码适用于一个单词,因此搜索器 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
4

1 回答 1

3

问题是你x在你的 Proc中指的是它在传递到searcher的参数上是封闭的,而你真正的意思是一次处理数组的每个元素。xtranslate

我更改了您的代码结构以更易于推理 - 通过消除匿名Proc并使用惯用的 Ruby 映射来处理字符串 - 无论是一个还是多个单词。

#!/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

到时候验证chmod +x pig_latin

./pig_latin "eat pie"
./pig_latin "eat"
于 2013-07-15T16:44:22.777 回答