Learning Ruby: Unpacking Arrays

October 25, 2010

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

The Right Way

Comments

  1. mark says:

    It is hard to google for the * character.

    That is why we need to repeat that its name is “splat operator”.

    And it turns things magically into an Array.

    :)

  2. John Hobbs says:

    Indeed it is.

    Here is a nice summary of the splat operator in Ruby: http://theplana.wordpress.com/2007/03/03/ruby-idioms-the-splat-operator/

Leave A Comment

Your email will not be published.