-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtsv_buddy.rb
27 lines (24 loc) · 867 Bytes
/
tsv_buddy.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
require 'csv'
# Module that can be included (mixin) to create and parse TSV data
module TsvBuddy
# @data should be a data structure that stores information
# from TSV or Yaml files. For example, it could be an Array of Hashes.
attr_accessor :data
attr_accessor :str
# take_tsv: converts a String with TSV data into @data
# parameter: tsv - a String in TSV format
# this method should take a String called `tsv` and convert
# it into a data structure to store in `@data`.
def take_tsv(tsv)
@data = CSV.parse(tsv, {:headers=>true, :col_sep=>"\t"}).map(&:to_hash)
end
# to_tsv: converts @data into tsv string
# returns: String in TSV format
def to_tsv
@str = ""
@str << @data.first.collect {|k,v| k}.join("\t")
@str << "\n"
@str << @data.collect {|i| "#{i.collect{|k,v| v}.join("\t")}\n"}.join
return @str
end
end