]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/lib/maasha/table.rb
adding table.rb
[biopieces.git] / code_ruby / lib / maasha / table.rb
1 # Copyright (C) 2013 Martin A. Hansen.
2
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
7
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16
17 # http://www.gnu.org/copyleft/gpl.html
18
19 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
20
21 # This software is part of the Biopieces framework (www.biopieces.org).
22
23 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
24
25 require 'maasha/filesys'
26
27 # Error class for all exceptions to do with Table.
28 class TableError < StandardError; end
29
30 class Table
31   def initialize(options = {})
32     @options = options
33     @header  = []
34     @table   = []
35
36     table_parse if @options[:file_in]
37   end
38
39   def rows
40     @table.size
41   end
42
43   def columns
44     @table.first.size
45   end
46
47   def each_row
48     @table.each do |row|
49       yield row
50     end
51
52     self
53   end
54
55   def each_column
56     @table.first.each_with_index do |key, i|
57       column = []
58       column << @header[i] unless @header.empty?
59
60       self.each_row { |r| column << r[i] }
61
62       yield column
63     end
64
65     self
66   end
67
68   def to_s
69     lines = []
70     lines << "#" + @header.join("\t") unless @header.empty?
71
72     self.each_row { |r| lines << r.join("\t") }
73     lines.join("\n")
74   end
75
76   private
77
78   def table_parse
79     File.open(@options[:file_in]) do |ios|
80       ios.each do |line|
81         if line[0] == '#'
82           if @header.empty?
83             @header = line[1 .. line.size].chomp.split(" ")
84
85             uniq = {}
86             
87             @header.each do |key|
88               raise TableError, "Duplicate header: #{key}" if uniq[key]
89               uniq[key] = true
90             end
91           end
92         else
93           fields = line.chomp.split(" ")
94
95           unless @header.empty? 
96             raise TableError, "Bad number of fields: #{fields.size} - expecting: #{@header.size}" unless @header.size == fields.size
97           end
98
99           @table << fields
100         end
101       end
102     end
103   end
104 end