有方法:
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."]
为什么会这样?
答案 0 :(得分:1)
我不确定输出与您的预期有何不同,但我会猜测推送.dup
ed字符串会有所帮助:
possible_queries.push(variant.dup)
这样,你在推送它之后对variant
所做的更改不会影响你已推送的内容,这似乎是你所期望的。
答案 1 :(得分: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