Heads up: This description was created by AI and might not be 100% accurate.
to_objects.rb
This Ruby code snippet demonstrates parsing a CSV file (“group.csv”) containing parent-child relationships and constructing a nested data structure representing families. It reads the CSV, then iterates through each row. If a row has a parent ID, it creates a new Family
object. If no parent ID is present, it assumes the child belongs to the last created family. The children are stored in the children
attribute of each Family
object, ultimately resulting in an array of Family
objects, each with its associated children.
Ruby code snippet
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:0x00007f04e78c6958
@children=["value0", "value1", "value2"],
@parent="id1">,
#<Family:0x00007f04e78c6818
@children=["value3", "value4", "value5", "value6", "value7"],
@parent="id2">,
#<Family:0x00007f04e78c67c8 @children=["value8", "value9"], @parent="id3">]
Executed with Ruby 3.4.5
.