我目前正在进行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
总是提示使代码更有效率(但对我来说最重要的是要理解为什么字符串范围不起作用)。 感谢。
答案 0 :(得分:1)
您的语句phonemes << ["qu", "sch", "thr"]
正在将该数组添加为phonemes
的最后一个元素,这就是include?
失败的原因。 <<
运算符旨在将单个元素添加到数组中。如果您想将该数组中的所有元素添加到phonemes
,则可以使用+=
运算符。
答案 1 :(得分:1)
这不是您的主要问题的答案,但您要求提供改进代码的提示。我建议你考虑使用一个案例陈述,你有很长的if-else。它使其更具可读性并减少重复。像这样:
result << case
when vowels.include?(word[0])
word + "ay"
when phonemes.include?(word[0..1])
"do something"
when phonemes.include?(word[0]) && phonemes.include?(word[1])
if phonemes.include?(word[2])
word[3..-1] + word[0..2] + "ay"
else
word[2..-1] + word[0..1] + "ay"
end
when phonemes.include?(word[0..1])
"do something else"
when phonemes.include?(word[0])
word[1..-1] + word[0]+ "ay"
else
"do something else or raise an error if you reach this point."
end
我没有密切关注你的代码,但我注意到你有phonemes.include?(word[0..1])
两次,所以第二个永远不会被执行。