As a novice it’s probably something about Ruby I missed, but for the life of me I don’t understand this result. So I have this simple function:
def crazyfunc(s)
s.gsub!('a', 'b')
#return has not purpose here
end
Now I have this simple few sets.
s1 = 'abc'
s2 = s1
s2 = crazyfunc(str2)
puts s1
=> bbc
Why in the world is s1 affected by crazyfunc? So doing this instead:
def crazyfunc(s)
return s.gsub('a', 'b')
end
doesn’t change str1, so I figure it’s got to do with what the inplace gsub is doing. But I still don’t get the logic of why str1 would be changed.
String assignment in Ruby doesn’t implicitly copy the string. You are simply assigning another reference to it. If you want to copy the string, use clone.
To demonstrate, you can check object IDs:
Since
aandbhave the same object ID, you know they’re the same object. If you want to modifybas a copy ofa, you can either use methods which return a new string (likegsubrather thangsub!), or you can useb = a.clone, and then operate onb.Or more simply: