0

我目前正在做 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

与往常一样,将不胜感激提高代码效率的提示(但对我来说最重要的是了解为什么字符串范围不起作用)。谢谢。

4

2 回答 2

1

您的声明phonemes << ["qu", "sch", "thr"]将该数组添加为 的最后一个元素phonemes,这就是include?失败的原因。该<<运算符旨在将单个元素添加到数组中。如果您想将该数组中的所有元素添加到phonemes您可以使用+=运算符,而不是。

于 2013-10-02T01:11:43.477 回答
1

这不是您主要问题的答案,但您要求提供改进代码的提示。我建议你考虑使用一个 case 语句,如果你有很长的 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])两次,所以第二次永远不会被执行。

于 2013-10-02T04:30:10.080 回答