我的代碼對於一個單詞工作正常,所以搜索器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
這是問問題的地方。 – sawa
歡迎來到Stack Overflow。對於第一個問題(+1)這非常好。我沒有使用過Ruby,但是我首先要做的就是分解'return array.collect(&searcher).join('')'語句,因爲它看起來像不解析你想分析的內容。或者也許可以簡化一些事情(可能使它變得不那麼類似Ruby),但要清楚地說明你在問題陳述中要做的事情,因爲那部分看起來很合理。 – John
@sawa我認爲OP的問題是「爲什麼不是這個代碼給出我想要的輸出?」 – John