sziep edited this page May 1, 2011 · 3 revisions
Clone this wiki locally

[A word of caution if you stumble upon it: This little piece of code was meant as an excersize in creating dynamic methods.]

This small addition to Rubys default CSV class, enhances it in a way that lets you iterate over columns in a nice way syntacticly E.g: given a csv dataset like:

Stephan,nick1,stephan@mail.de,"A first message",3
Nico,nick2,nico@mail.de,"A second message",6
Richard,nick3,richard@mail.de,"A third message",67
Marc,nick4,marc@mail.de,"A fourth message",1234

You can directly refer to the header (downcased) in the foreach method like this:

OPTIONS = { converters:         :all,
            headers:            true,
            header_converters:  :downcase}

CSV.foreach_message("data.csv", OPTIONS).each do |msg|
  p msg

CSV.foreach_message_and_nickname("data.csv", OPTIONS).each do |msg|
  p msg