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!

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!


» Post a Comment

Who we are:
The Pasadena Ruby Brigade is a group of programmers who are interested in Ruby. We enjoy sharing our ideas and code with anyone who is interested in this wonderful programming language.

Who can join:
Anyone! Just head over to our mailing list and drop us an email.

What we do:
We recently started a project over at RubyForge. This project is a group of programs written and maintained by our members that we thought could be beneficial to the whole community.



Recent Posts