Reputation: 121
I am attempting to write a method that changes one string to another one letter at a time. However, I never noticed in ruby that if you push a string variable to an array it seems to push the address of the string variable and not the string.
def mutate_my_strings(s1,s2)
#your code here
str1 = s1.to_s
str2 = s2.chars
ret = []
puts str1
ret.push(str1)
s1.chars.each_with_index do |q,idx|
str1[idx] = str2.shift
ret.push(str1)
end
return ret.join("\n")
end
mutate_my_strings("bubble gum", "turtle ham")
This output shows that the enumerable modifies the str1 but the out for the puts the string "bubble gum" turn into "turtle ham" This isn't so in the array. The entire string is modified in the array:
bubble gum
"tubble gum"
"tubble gum"
"turble gum"
"turtle gum"
"turtle gum"
"turtle gum"
"turtle gum"
"turtle hum"
"turtle ham"
"turtle ham"
=> "turtle ham\nturtle ham\nturtle ham\nturtle ham\nturtle ham\nturtle ham\nturtle ham\nturtle ham\nturtle ham\nturtle ham\nturtle ham"
Upvotes: 2
Views: 85
Reputation: 30473
Replace ret.push(str1)
with ret.push(str1.dup)
to create a new string every time.
And here is a more elegant solution to the problem:
def mutate_strings(s1, s2)
(0...s1.size).map { |i| s2[0..i] + s1[i+1..-1] }.join("\n")
end
puts(mutate_strings('bubble gum', 'turtle ham'))
Upvotes: 1
Reputation: 121
I fix it by adding:
ret.push(str1) to
ret.push(str1 * 1)
This creates a new pointer every iteration
Upvotes: 0