如何通过将字符串更改为结束的循环来满足此条件?

时间:2012-09-15 03:04:38

标签: ruby string loops

我将一个单词与另一个单词进行比较,该单词通过循环字母表并在单词的每个位置插入每个字母来改变。

@position_counter = 0

编辑:这是letter_loop正在运行的代码。

@array = ["amethod", "variable", "block"]

def word_list_loop
  @match_counter = 0
  @array.each do |word|
    letter_loop(word)
  end
  puts @match_counter
end

关闭编辑

def letter_loop(word)
  ("a".."z").each do |letter|
     word_plus_letter = @word.dup
     word_plus_letter.insert(@position_counter, letter)
     @match_counter+=1 if word.match(/\A#{word_plus_letter}\z/)
  end
  @position_counter+=1
  letter_loop(word) unless @position_counter == (@word.length + 1) 
end

我用于参数的单词是"method"。但是当我运行这个时,我得到了index 7 out of string (IndexError)。它正确地循环遍历每个位置的字母表,但它似乎没有被unless @position_counter == (@word.length + 1)捕捉到结束。

我已尝试过其他一些方法,使用if语句等,但我无法让方法完成。

1 个答案:

答案 0 :(得分:1)

您运行letter_loop的次数是多少?你确定错误发生在第一次运行中吗?从我看到的情况来看,如果你第二次调用它而不将@position_counter重置为零,它将以@word.length + 1开头,产生你看到的确切错误。除此之外,我发现你的代码没有任何问题(在第一次运行时运行得很好)。

更新,因为您使用的是递归解决方案,并且position_counter不代表您的程序状态(只是方法调用的状态),我建议不要将其声明为@position_counter,但作为方法的可选参数:

def letter_loop(word, position_counter=0)
  ("a".."z").each do |letter|
     word_plus_letter = @word.dup
     word_plus_letter.insert(position_counter, letter)
     @match_counter+=1 if word.match(/\A#{word_plus_letter}\z/)
  end
  position_counter+=1
  letter_loop(word, position_counter) unless position_counter == (@word.length + 1) 
end

如果您不能/不想这样做,只需在每次使用之前/之后重置它,就像我之前建议的那样,它会正常工作:

@array.each do |word|
  @position_counter = 0
  letter_loop(word)
end

(虽然我不建议使用第二种方法,因为如果你忘记在其他地方重置它,你的方法会再次失败)