0

有方法:

possible_queries=[]
variant="tenra"
for i in 0...variant.length
  variant="tenra"
  if variant[i]=~/[\w]/
    letter=variant[i]
    variant[i]="."
    for k in 0...variant.length
      if variant[k]=~/[\w]/ && i!=k
        letter_two=variant[k]
        variant[k]="."
        possible_queries.push(variant)
        print variant+", "
        variant[k]=letter_two
      end
    end
  end
end
print "\n"
print possible_queries.inspect

所以我variant在每个内部循环上发送到数组,并在这里打印它,但实际上variant发送到数组的项目与实际的数组项目不匹配。

印刷变体:

..nra, .e.ra, .en.a, .enr., ..nra, t..ra, t.n.a, t.nr., .e.ra, t..ra, te..a, te.r., .en.a, t.n.a, te..a, ten.., .enr., t.nr., te.r., ten.., 

和 possbile_queries:

[".enra", ".enra", ".enra", ".enra", "t.nra", "t.nra", "t.nra", "t.nra", "te.ra", "te.ra", "te.ra", "te.ra", "ten.a", "ten.a", "ten.a", "ten.a", "tenr.", "tenr.", "tenr.", "tenr."]

为什么是这样?

4

2 回答 2

1

我不确定输出与您的期望有何不同,但我会试一试并猜测推动.duped 字符串会有所帮助:

possible_queries.push(variant.dup)

这样,您variant在推送后所做的更改不会影响您已经推送的内容,这似乎是您所期望的。

于 2013-06-15T17:37:31.263 回答
0

该错误比您想象的要简单。您在推送中添加到数组中的是指向文本的指针。然后我的朋友您更改了指针的内容(在您打印它之后。

  possible_queries.push(variant)   #reference to the object (aka pointer) variant
  print variant+", "               #prints the object (staticly)
  variant[k]=letter_two            #you changed the object variant..  
                                   #the value in the array is still pointing to the object and you've changed its contents. 

简单的解决方案..当您推送到数组时..添加 dup..

variant.dup 
于 2013-06-16T11:16:31.067 回答