To_objects.rb
This content was produced by an LLM and could include errors.
このスクリプトは親子構造のCSV(group.csv)を読み込んでオブジェクトへ組み立てます。parent が入力されている行で Family オブジェクトを新規作成し、parent が空欄の child 行は arr.last.children へ追加していきます。結果として arr には id1〜id3 の3家族が children 配列つきで格納され、フラットなCSVから階層データを作る典型例となっています。
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:0x00007f9b66c99c90
@children=["value0", "value1", "value2"],
@parent="id1">,
#<Family:0x00007f9b66c99b00
@children=["value3", "value4", "value5", "value6", "value7"],
@parent="id2">,
#<Family:0x00007f9b66c99920 @children=["value8", "value9"], @parent="id3">]
Ruby 4.0.6