Search code examples
rubystringindices

String assignment does not work properly


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.


Solution

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