To_objects.rb

This content was produced by an LLM and could include errors.

This script reads CSV data and organizes records into Family objects. It processes flat data by grouping associated children, assigning them either to a specified parent or to the most recently created family.

require "csv"
#=> true
data = CSV.read("input/text/group.csv", encoding: "BOM|UTF-8", headers: true).map(&:to_h)
#=> [{"parent" => "id1", "child" => "value0"},
#...

class Family
  attr_accessor :children
  
  def initialize(parent)
    @parent = parent
    @children = []
  end
end
#=> :initialize

arr = []
#=> []
data.each do |hash|
  parent = hash["parent"]
  if parent.nil?
    arr.last.children << hash["child"]
    else
    arr << Family.new(parent)
    arr.last.children << hash["child"]
  end
end
#=> [{"parent" => "id1", "child" => "value0"},
 {"parent" => nil, "child" => "value1"},
 {"parent" => nil, "child" => "value2"},
 {"parent" => "id2", "child" => "value3"},
 {"parent" => nil, "child" => "value4"},
 {"parent" => nil, "child" => "value5"},
 {"parent" => nil, "child" => "value6"},
 {"parent" => nil, "child" => "value7"},
 {"parent" => "id3", "child" => "value8"},
 {"parent" => nil, "child" => "value9"}]

arr
#=> [#<Family:0x00007f5195c05290
  @children=["value0", "value1", "value2"],
  @parent="id1">,
 #<Family:0x00007f5195c05100
  @children=["value3", "value4", "value5", "value6", "value7"],
  @parent="id2">,
 #<Family:0x00007f5195c04f20 @children=["value8", "value9"], @parent="id3">]

Ruby 4.0.3