Emilio
Emilio

Reputation: 2109

Beginner Trying to Find Out Why 2 Very Similar Sets of Code Have Very Different Results

The first set of code works

https://repl.it/Br7w/1069

def scramble_string(string, positions)
  scrambled=""
  idx=0
  while idx<string.length
    scrambled+=string[positions[idx]]
    idx+=1
  end
  puts scrambled
  return scrambled
end

It results in the following inputs/outputs:

scramble_string("abcd", [3, 1, 2, 0]) == "dbca"

scramble_string("markov", [5, 3, 1, 4, 2, 0]) == "vkaorm"

On the other hand, this 2nd set doesn't work

https://repl.it/Br7w/1072

def scramble_string(string, positions)
  scrambled=string
  idx=0
  while idx<string.length
    scrambled[idx]=string[positions[idx]]
    idx+=1
  end
  puts scrambled
  return scrambled
end

It results in the following inputs/outputs:

scramble_string("abcd", [3, 1, 2, 0]) == "dbcd"

scramble_string("markov", [5, 3, 1, 4, 2, 0]) == "vkkokv"

Please help me understand why the 2nd set doesn't work.

Upvotes: 1

Views: 57

Answers (2)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33430

Because in the second scrambled_string method you're initializing your scrambled variable as the string is being passed as the first parameter, not as an empty string.

def scramble_string(string, positions)
  scrambled = ''
  idx = 0
  while idx < string.length
    scrambled[idx] = string[positions[idx]]
    idx += 1
  end
  scrambled
end

p scramble_string('abcd', [3, 1, 2, 0])
# => "dbca"
p scramble_string('markov', [5, 3, 1, 4, 2, 0])
# => "vkaorm"

This is what happens in both cases:

markov           markov
v                v
markov           varkov
k                k
markov           vkrkov
a                k
markov           vkkkov
o                o
markov           vkkoov
r                k
markov           vkkokv
m                v
"vkaorm"         "vkkokv"

Upvotes: 2

Matt
Matt

Reputation: 20796

In ruby, strings are assigned by reference. That is, after

scrambled=string

any changes to scrambled will also change string.

If you replace that line with

scrambled=string.dup

which gives scrambled its own copy, then the functions will give the same output.

Upvotes: 1

Related Questions