module Tafel
Constants
- VERSION
Public Class Methods
flatten(table)
click to toggle source
# File lib/tafel.rb, line 74 def self.flatten(table) fail ArgumentError.new('not a table') unless table?(table) flat = true table = table.collect { |r| r.collect { |c| next c unless table?(c); flat = false; flatten(c) } } return table if flat ss = table.collect { |r| r.collect { |c| size(c) } } ss.each do |row| maxh = row.collect { |cell| cell[1] }.max maxh = maxh < 1 ? 1 : maxh row.each { |cell| cell[1] = maxh } end ss.collect { |row| row.size }.max.times do |x| maxw = ss.collect { |row| cell = row[x]; cell ? cell[0] : 1 }.max maxw = maxw < 1 ? 1 : maxw ss.each { |row| cell = row[x]; cell[0] = maxw if cell } end w = ss.first.collect(&:first).reduce(&:+) h = ss.collect { |row| row[0].last }.reduce(&:+) a = Array.new(h) { Array.new(w) } iterate(ss) do |x, y, s| next unless s left = x > 0 ? ss[y][x - 1] : nil above = y > 0 ? ss[y - 1][x] : nil woff = left ? left[2] + left[0] : 0 hoff = above ? above[3] + above[1] : 0 s.push(woff, hoff) copy(a, woff, hoff, table[y][x]) end a end
table?(o)
click to toggle source
# File lib/tafel.rb, line 30 def self.table?(o) o.is_a?(Array) && o.all? { |r| r.is_a?(Array) } end
to_htable(x)
click to toggle source
# File lib/tafel.rb, line 49 def self.to_htable(x) kla0 = narrow_class(x) kla1 = nil if kla0 vs = x.respond_to?(:values) ? x.values : x kla = narrow_class(vs.first) kla1 = vs.all? { |v| kla ? v.is_a?(kla) : false } ? kla : nil end #p [ kla0, kla1 ] case [ kla0, kla1 ] when [ Hash, Hash ] then to_h_hash_hash(x) when [ Array, Hash ] then to_h_array_hash(x) when [ Hash, nil ] then to_h_hash(x) else x end end
Also aliased as: to_h
to_vtable(x, limit=-1)
click to toggle source
.to_vtable: keys are arrayed vertically (y explosion) .to_htable: keys are arrayed horizontally (x explosion)
# File lib/tafel.rb, line 38 def self.to_vtable(x, limit=-1) return x if limit == 0 case x when Hash then x.to_a.collect { |k, v| [ k, to_vtable(v, limit - 1) ] } when Array then x.inject([]) { |a, e| a << [ a.size, to_vtable(e) ]; a } else x end end
Also aliased as: to_v