csvrecord - read in comma-separated values (csv) records with typed structs / schemas

7 views
Skip to first unread message

Gerald Bauer

unread,
Aug 12, 2018, 2:10:50 PM8/12/18
to www...@googlegroups.com
Hello,

I've put together a new library / gem called csvrecord [1] that
let's you read in comma-separated values (csv) records
with typed structs / schemas. Example.

beer.csv:
```
Brewery,City,Name,Abv
Andechser Klosterbrauerei,Andechs,Doppelbock Dunkel,7%
Augustiner Bräu München,München,Edelstoff,5.6%
Bayerische Staatsbrauerei Weihenstephan,Freising,Hefe Weissbier,5.4%
Brauerei Spezial,Bamberg,Rauchbier Märzen,5.1%
Hacker-Pschorr Bräu,München,Münchner Dunkel,5.0%
Staatliches Hofbräuhaus München,München,Hofbräu Oktoberfestbier,6.3%
```

Step 1: Define a (typed) struct for the comma-separated values (csv)
records. Example:

require 'csvrecord'

Beer = CsvRecord.define do
field :brewery ## note: default type is :string
field :city
field :name
field :abv, Float ## allows type specified as class (or use :float)
end

# or in "classic" style:

class Beer < CsvRecord::Base
field :brewery
field :city
field :name
field :abv, Float
end


Step 2: Read in the comma-separated values (csv) datafile. Example:

beers = Beer.read( 'beer.csv' ).to_a

puts "#{beers.size} beers:"
pp beers

pretty prints (pp):

6 beers:
[#<Beer:0x302c760
@abv = 7.0,
@brewery = "Andechser Klosterbrauerei",
@city = "Andechs",
@name = "Doppelbock Dunkel">,
#<Beer:0x3026fe8
@abv = 5.6,
@brewery = "Augustiner Br\u00E4u M\u00FCnchen",
@city = "M\u00FCnchen",
@name = "Edelstoff">,
...
]

Or loop over the records. Example:

Beer.read( data ).each do |rec|
puts "#{rec.name} (#{rec.abv}%) by #{rec.brewery}, #{rec.city}"
end

printing:

Doppelbock Dunkel (7.0%) by Andechser Klosterbrauerei, Andechs
Edelstoff (5.6%) by Augustiner Bräu München, München
Hefe Weissbier (5.4%) by Bayerische Staatsbrauerei Weihenstephan, Freising
Rauchbier Märzen (5.1%) by Brauerei Spezial, Bamberg
Münchner Dunkel (5.0%) by Hacker-Pschorr Bräu, München
Hofbräu Oktoberfestbier (6.3%) by Staatliches Hofbräuhaus München, München


Or create new records from scratch. Example:

beer = Beer.new( brewery: 'Andechser Klosterbrauerei',
city: 'Andechs',
name: 'Doppelbock Dunkel' )

And so on and so forth.
Happy hacking and data wrangling with ruby. Cheers. Prost.


[1] https://github.com/csv11/csvrecord
Reply all
Reply to author
Forward
0 new messages