Joe Half Face
Joe Half Face

Reputation: 2333

What goes in array doesn't match output while looping

There is method:

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

So I send variant to array on each inner loop, and print it here for example, but actually variant item which is sent to array doesn't match actual array item.

Printed variants:

..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.., 

And 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."]

And why is that?

Upvotes: 0

Views: 69

Answers (2)

MollyCat
MollyCat

Reputation: 495

The error is simpler than you may think.. What you're adding to the array in the push is a pointer to the text.. Then my friend you change the contents of the pointer (after you've printed it.

  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. 

Simple solution.. when you push to the array.. add dup..

variant.dup 

Upvotes: 0

Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34031

I'm not sure how the output differs from your expectations, but I'll take a stab and guess that pushing a .duped string will help:

possible_queries.push(variant.dup)

That way the changes you make to variant after pushing it won't affect what you've already pushed, which seems to be what you expect.

Upvotes: 1

Related Questions