At various times I find myself with an ‘array of hashes’ in my ruby script, and I want to write them out to a csv file. I know I can use FasterCSV for this.
My question is, what if I want to specify certain fields? How can I do this without having to do the hash filtering myself? Ideally I could specify the field list to FasterCSV, then append the hashes. FasterCSV would then take care of filtering the values to the keys that match the specified fields and do the rest.
Python has a lib called DictWriter which can do this.
Ok, I asked your question to James (author of FasterCSV), and here’s his answer:
If you have array of hashes, say
And you want only :a and :b keys, you may do the following:
Hope that helps.