我目前正在做 Test First 的 rspec 教程,并且有一个与 Pig_Latin 问题有关的问题。
具体来说,我想了解字符串范围。这是我的代码的一部分:
if phonemes.include?(word[0]) && phonemes.include?(word[1]) && phonemes.include?(word[2])
<do something>
end
而不是上面我试过:
if phonemes.include?(word[0..2]) # i added that character to the list of phonemes
<do something> # e.g. if the word is school i added "sch" to
end # the array called phonemes
"sch"
但是,即使在phonemes
并且它也不起作用word[0..2] == "sch"
我的问题是为什么我不能使用字符串范围来操纵结果。(如果不清楚,我将在底部发布我的完整代码)
代码(正在进行中):
def translate(string)
array = string.split(" ")
alphabet = ("a".."z").to_a
vowels = ["a", "e", "i", "o", "u"]
phonemes = alphabet - vowels
phonemes << ["qu", "sch", "thr"]
result = []
array.each do |word|
if vowels.include?(word[0])
result << (word + "ay")
elsif phonemes.include?(word[0..1])
result << "do something"
elsif phonemes.include?(word[0]) && phonemes.include?(word[1]) && phonemes.include?(word[2])
result << (word[3..-1] + (word[0..2] + "ay"))
elsif phonemes.include?(word[0]) && phonemes.include?(word[1])
result << (word[2..-1] + (word[0..1] + "ay"))
elsif phonemes.include?(word[0..1])
result << "do something else"
elsif phonemes.include?(word[0])
result << (word[1..-1] + (word[0]+ "ay"))
end
end
return result.join(" ")
end
与往常一样,将不胜感激提高代码效率的提示(但对我来说最重要的是了解为什么字符串范围不起作用)。谢谢。