On-the-floor

On the Floor

Ruby Gotcha With Array::uniq!

Here's one from the "I-Banged-My-Head-Against-The-Wall-Trying-To-Figure-This-Out-So-I'll-Post-This-So-You-Don't-Have-To" Department:

I had a method that added a bunch of stuff to an array, then did some clean-up to it before returning it.  The method initially had some working code in it like this:

def get_stuff
  # collect stuff here...
  stuff.uniq!
  stuff.sort! { |x,y| x.list_order <=> y.list_order }
end

Then, I realized that the method shouldn't sort the array, so I deleted the last line, like so:

def get_stuff
  # collect stuff here...
  stuff.uniq!
end

At some point later, I noticed that my app was sometimes broken and sometimes worked fine, and then spent a bunch of time trying to figure out why.  I got some other people involved and then Mark said, "Oh, I've done that before."

Can you see the annoyance in my code that Mark saw right away?

It turns out that Array::uniq! will return itself, i.e. a unique array ONLY IF IT ACTUALLY DID SOMETHING.  Otherwise, it returns nil.  So, when I deleted the line of code that did the sorting, I introduced the possibility that my method would sometimes return the value I was expecting, and sometimes not.

Arrgh.

Comments

There are no comments to display.

Add a Comment

Your Comment:

Your Name:

Your Email Address: (Won't be published)

Your Website: (If you've got one)