0

I am trying to write a function that takes a string and takes desired indices and scrambles the string:

def scramble_string(string, positions)
  temp = string
  for i in 0..(string.length-1)
   temp[i] = string[positions[i]]
  end
  puts(string)
  return temp
end

When I call the above method, the "string" is altered, which you will see in the output of puts.

Why does this happen since I didn't put string on the left-hand side of an equation I wouldn't expect it to be altered.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • 3
    [Possible duplicate](http://stackoverflow.com/questions/1465569/ruby-how-can-i-copy-a-variable-without-pointing-to-the-same-object) – rdupz Mar 26 '16 at 19:10
  • When asking, please supply example input and your expected output. See "[mcve]". – the Tin Man Mar 26 '16 at 22:06
  • While not a duplicate, http://stackoverflow.com/a/1872159/128421 will explain what's happening very nicely. – the Tin Man Mar 26 '16 at 22:19

1 Answers1

1

You need a string.dup:

def scramble_string(string, positions)
  temp = string.dup
  for i in 0..(string.length-1)
   temp[i] = string[positions[i]]
  end
  puts(string)
  return temp
end

For more understanding try the following snippet:

  string = 'a'
  temp = string
  puts string.object_id      
  puts temp.object_id      

The result of two identical object ids, in other words, is that both variables are the same object.

With:

  string = 'a'
  temp = string.dup
  puts string.object_id      
  puts temp.object_id      

  puts string.object_id == temp.object_id   #Test for same equal -> false   
  puts string.equal?( temp) #Test for same equal -> false
  puts string == temp #test for same content -> true

you get two different objects, but with the same content.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
knut
  • 27,320
  • 6
  • 84
  • 112