Rookie Ruby Mistake
Thursday, October 12, 2006 by Nate Murray.
I made a rookie mistake today, so I thought I'd share it. Consider the following code:
s = "hello world" a = ["foo", "bar", s] other_s = s # not a copy! other_s.upcase! puts a[2] # => "HELLO WORLD"
Notice that the contents of a were changed. This is because the variable other_s is simply a reference to the same object that is in a. It's such a simple thing to overlook when things are more complicated. It's subtle and that can make it difficult to track down.
The lesson? When you edit an object in place make sure that is what you want!
Labels: ruby