Learning Ruby: Unpacking Arrays

So, about a week or go I dove back into Ruby out of necessity. The Twitter daemon I had written in Python for Confurrent was chronically ill. My socket would block and eat 100% CPU and it seemed like nobody knew how to work around it, least of all me.

So I pulled out Ruby. I've only ever done any real Ruby work with Rails, when I wrote ThirtyDayList to learn the tech.

One thing I will note is that learning Rails basics does not teach you Ruby, or at least not enough Ruby to be useful. However, writing my Twitter daemon has made me confident in Ruby, and I like it a lot more now than after the Rails experiment.

The daemon was quick to write, using Tweetstream, and I only ran into one roadblock, which was all my fault.

See, I wanted to use the track method, which takes an unlimited and variable set of arguments (like *args in Python) but I had my arguments in an array. I could not figure out how to pass those on correctly, and even bust into the gem and started adding code to get it to work.

I finally realized that there is no way that there isn't a built-in for this and I went back to Googling. A short while later I found a short post from detailing exactly what I should be doing.

Evidently you can use the asterisk to unpack an array for this. Super easy, but I feel silly for not finding that sooner. The pitfalls of unfocused autodidactism.

The Wrong Way

predicates = [ 'a', 'b', 'c' ]
@client.track( predicates )
# Tracks 'abc'

The Right Way

predicates = [ 'a', 'b', 'c' ]
@client.track( *predicates )
# Tracks 'a,b,c'