0

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?

2
  • You should do a little better job at asking. I have no idea, what's wrong with the code, what do you expect and why do you expect that? Commented Jun 15, 2013 at 17:27
  • @SergioTulentsev, I want simple thing - possible_queries to contain printed varints. And I have no idea, why when i print variant - it is ok, send it to array, and then array items are nothing close to what have been printed before sending Commented Jun 15, 2013 at 17:37

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man! I thought that if I send before changing variable, it won't affect sent one.
0

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.