class Origen::Utility::CSV
A class to handle the parsing of Comma Separated Value
(CSV
) input data Field names are indicated on first line of file, separated by comma Field values are indicated on all lines after first line of file, separated by comma All lines must have same number of fields names and values
Public Class Methods
Source
# File lib/origen/utility/csv_data.rb, line 10 def initialize(file) @file = file end
Supply a path to the CSV
file, this should be a relative path from the top level of your project workspace (Origen.root
)
Public Instance Methods
Source
# File lib/origen/utility/csv_data.rb, line 53 def fields extract_csv_data(field_names_only: true) end
Parses the data and returns only the field values (keys) defined in the first line of the file opens file but only reads first line
Example¶ ↑
csv = CSV.new("/path/to/data.csv") field_names = csv.fields
Source
# File lib/origen/utility/csv_data.rb, line 58 def num_fields fields.length end
Number of fields in file
Source
# File lib/origen/utility/csv_data.rb, line 35 def parse(options = {}) csv_data = extract_csv_data(options) if block_given? # doesn't do much at this point csv_data.each do |dataset| yield dataset end else csv_data end end
Parses the CSV
file and returns an array of hashes where each hash represents one line of data. Hash
keys obtained from first line of field names. Optionally if block supplied, it will return a single line from CSV
file at a time
Example¶ ↑
csv = CSV.new("/path/to/data.csv") Process data yourself data = csv.parse data.each do |dataline| dataline.keys.each do |key| print "Key: #{key}, Value: #{dataline[key]}\n" end end Let parse process data (not much diff) csv.parse do |dataline| dataline.keys.each do |key| print "Key: #{key}, Value: #{dataline[key]}\n" end end
Source
# File lib/origen/utility/csv_data.rb, line 64 def valid_fields?(check_fields = []) fields.eql?(check_fields) end
Checks fields to ensure they exist Input: array of fields expected