Reputation: 2109
The first set of code works
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
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
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
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