user14069773
user14069773

Reputation: 175

Ruby - Equivalent object for Datatable?

In c# there is the DataTable object which is a nice Data Structure. In Ruby I cannot think of a similar object, not even a hash with sub arrays/hashes like so:

hash = { val: [] }

I want to be able to construct a new DataTable object and add columns and rows to it. Any ideas?

Upvotes: 0

Views: 128

Answers (2)

benjessop
benjessop

Reputation: 1959

Observe the DataTable object in c# and what is happening

DataTable dt = new DataTable();
dt.Columns.Add("some_column");
dt.Rows.Add("some_row")

In ruby classes are blueprints for objects so custom classes are going to have to be made. In the example above you can see three classes: DataTable Columns and Rows

Replicating in Ruby

The below is full of bugs no doubt, but would give you a basic idea on how to start creating a custom data structure.

class DataTable
  attr_reader :rows, :columns, :row

  def initialize(table_name)
    @rows = []
    @columns = [ DataColumn.new("id") ]
    @primary_key = 0
    @selected_row = nil
  end

  def add_row
    @rows << DataRow.new(@columns, @primary_key)
    @primary_key += 1
  end

  def add_column(column_name)
    @columns << DataColumn.new(column_name)
    @rows.map { |row| row.add_column(column_name) }
  end

  def select_row(id)
    @rows.map(&:values).map { |row| row["id"].to_s == id.to_s ? @row = row : nil }
    @row
  end

  alias_method :[], :select_row

  def update_row(col, val)
    return unless @rows.keys.include? col
    
    @row[col] = val
  end
end

class DataColumn
  attr_accessor :column_name

  def initialize(column_name)
    @column_name = column_name
  end
end

class DataRow
  attr_accessor :values

  def initialize(columns, primary_key)
    @values = columns.map(&:column_name).product([nil]).to_h
    @values["id"] = primary_key
  end

  def add_column(column)
    @values[column] = nil unless @values[column]
  end
end

then you do the following:

 d = DataTable.new("table_1")
 d.add_row
 d.add_row
 d.add_column("col_1")
 d.add_column("col_2")
 d[0]["col_1"] = "some_val"

Upvotes: 0

Kumar
Kumar

Reputation: 3126

Why not create a class with the desired structure in your mind and methods to add rows and columns etc.

Example (for basic demonstrate only):

class DataTable
  attr_accessor :columns, :rows, :table

  def initialize()
    self.columns = []
    self.rows = []
  end

  def add_column(column_name)
    self.columns.push(column_name)
  end

  def add_row(row = {})
    self.rows.push(row)
  end
end

# Create a new datatable
datatable1 = DataTable.new

datatable1.add_column('id')
datatable1.add_row([1])

puts datatable1.columns # ['id']
puts datatable1.rows[0] # [1]

You can decide how to structure of your data and have more methods to help you what you would like to achieve.

Upvotes: 1

Related Questions