Ruby Quick Reference

Quick reference for efficient coding

View the Project on GitHub YumaYX/RubyQuickReference

to_objects.rb(text)

This Ruby code reads a CSV file named “group.csv” with UTF-8 encoding and parses it into an array of hashes. It defines a Family class with an initialize method to set the parent and an empty children array, and an attribute accessor for children. The script iterates over each hash in the data, checks if the “parent” key is nil, and if so, adds the child to the last family’s children array. If the “parent” key is present, it creates a new Family instance and adds the child to its children array. Finally, it returns the array of Family instances.

Execution:

require "csv"
#=> true
data = CSV.read("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:0x00007f814033d268
  @children=["value0", "value1", "value2"],
  @parent="id1">,
 #<Family:0x00007f814033d060
  @children=["value3", "value4", "value5", "value6", "value7"],
  @parent="id2">,
 #<Family:0x00007f814033cf98 @children=["value8", "value9"], @parent="id3">]

Executed with Ruby 3.3.5