Method: FatTable::Column#initialize

Defined in:
lib/fat_table/column.rb

#initialize(header:, items: [], type: 'NilClass', tolerant: false) ⇒ Column

Create a new Column with the given +header+ and initialized with the given +items+, as an array of either strings or ruby objects that are one of the permissible types or strings parsable as one of the permissible types. If no +items+ are passed, returns an empty Column to which items may be added with the Column#<< method. The item types must be one of the following types or strings parseable as one of them:

Boolean:: an object of type TrueClass or FalseClass or a string that is either 't', 'true', 'y', 'yes', 'f', 'false', 'n', or 'no', in each case, regardless of case.

DateTime:: an object of class Date, DateTime, or a string that matches +/\d\d\d\d[-\/]\d\d?[-\/]\d\d?/+ and is parseable by DateTime.parse.

Numeric:: on object that is of class Numeric, or a string that looks like a number after removing '+$+', '+,+', and '+_+' as well as Rationals in the form /:/ or /, where is an integer.

String:: if the object is a non-blank string that does not parse as any of the foregoing, it its treated as a Sting type, and once a column is typed as such, blank strings represent blank strings rather than nil values.

NilClass:: until a Column sees an item that qualifies as one of the foregoing, it is typed as NilClass, meaning that the type is undetermined. Until a column obtains a type, blank strings are treated as nils and do not affect the type of the column. After a column acquires a type, blank strings are treated as nil values except in the case of String columns, which retain them a blank strings.

Examples:


require 'fat_table'
col = FatTable::Column.new(header: 'date')
col << Date.today - 30
col << '2017-05-04'
col.type #=> 'DateTime'
col.header #=> :date
nums = [35.25, 18, '35:14', '$18_321']
col = FatTable::Column.new(header: :prices, items: nums)
col.type #=> 'Numeric'
col.header #=> :prices
col.sum #=> 18376.75

Parameters:

  • header (String, Symbol)

    the name of the column header

  • items (Array<String>, Array<DateTime>, Array<Numeric>, Array<Boolean>) (defaults to: [])

    the initial data items in column

  • type (String) (defaults to: 'NilClass')

    the column type: 'String', 'Numeric', 'DateTime', 'Boolean', or 'NilClass'

  • tolerant (Boolean) (defaults to: false)

    whether the column accepts unconvertable items not of its type as Strings

Raises:



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/fat_table/column.rb', line 94

def initialize(header:, items: [], type: 'NilClass', tolerant: false)
  @raw_header = header
  @header =
    if @raw_header.is_a?(Symbol)
      @raw_header
    else
      @raw_header.to_s.as_sym
    end
  @type = type
  @tolerant = tolerant
  msg = "unknown column type '#{type}"
  raise UserError, msg unless TYPES.include?(@type.to_s)

  @items = []
  items.each { |i| self << i }
end