Wednesday, December 05, 2007

Stupid Ruby Mistake

And by that I mean stupid thing I did.  The << notation is a great way to chain things together.  It's a little like +=, but it's flexible enough to work with strings or arrays and do the right thing.  When I need to build up an array or something I'll almost always do it like this:

ret=[]

Object.find(:all).each { |o|

 ret << o.value

}

and presto, I have my array.  Or when building strings:

url = config[:webserviceurl]<<"/controller/action?"<<params.join("&")

 

Oops.  <<, if you didn't know it, is destructive in the case of strings and arrays(*).  b = a << ", world"

Then not only does b equal "hello, world" but I just changed the value of a as well! 

 

That took me a little while to find.  Even worse, it was working fine for me in development mode for my Rails app.  It was only when I switched to production that it showed up.  Must have something to do with the string storage?

Anyway, just thought I'd blog it and save somebody else the stupid mistake.

 

(*) In the case of numerics, << means a completely different thing.  It's a bitshift.  So if a=1 then a<<2 is 4.

No comments: