1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Building Hashes


5 of 5

Building Hashes From Arrays

It's often useful to build hashes from an array. This can be done easily using the Hash[ … ] syntax. It'll take an unlimited number of arguments (as long as it's an even number), taking two at a time and using the first as a key, the second as a value. So, for example, Hash[ :key1, 'value', :key2, 'value' ] is equivalent to {:key1 => 'value', :key2 => 'value' }.

This is useful in all manner of situations. Suppose, for example, you're reading some comma-separated values from a text file, and you wish to turn each row into a hash. The first line holds the column names. How do you read this file and turn it into an array of hashes?

First, let's read the first line and zip it with the column indexes. "Zipping" two arrays will combine them. So, if you were to zip ['a', 'b', 'c'] with [1,2,3], you would get [ ['a',1], ['b',2], ['c',3] ]. If you were to then flatten then to produce [ 'a', 1, 'b', 2, 'c', 3 ] and then splat it and pass it to Hash[ … ], you would get a hash equivalent to {:a => 1, :b => 2, :c => 3}. This sounds complicated, but it's not difficult once you start playing with it, and very powerful.

The code is pretty straightforward. The first part just loads the columns names and keeps them for use in the next line. The next line does all the work, and it helps to read it inside-out. For each line, split on commas, zip with the column names, flatten the list, splat it and pass it to the special Hash constructor.

#!/usr/bin/env ruby
require 'pp'

def readcsv(file)
 File.open(file) do|f|
    columns = f.readline.chomp.split(',')
    f.readlines.map{|l| Hash[ *columns.zip(l.chomp.split(',')).flatten ] }

pp readcsv('data.csv')

  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. Building Hashes From Arrays

©2014 About.com. All rights reserved.