Ruby Pro Tip: Arrays

If I had to break down all the things I learned at RailsConf into individual items, I think most people would be surprised which individual items sees the most usage when I'm giving tips to someone else on their Ruby code. When working with an item that I need to be an array, and yet have no idea what it actually is, people frequently use an if:

if result.class != "Array"

  result = [result]

Or, some people will use the more compacted method of a ternary operator:

result = result.class == "Array" ? result : [result]

However, the Array class is already equipped for a more confident method:

result = Array(result)

The Array class' initialize method already returns an array of any class you pass it, with the exception of another Array. If you pass it an Array already it will simply return the original Array.

It's quite a simple tip, but I've been extremely surprised how infrequently used it is, and how often I've used it or passed it along since I got back from RailsConf. Big thanks to Avdi Grimm for his amazing lecture Confident Code at RailsConf 2011.