Heads up: This description was created by AI and might not be 100% accurate.

objects_to_text.rb

This Ruby code snippet demonstrates iterating through an array of hashes, extracting data from each hash (specifically :id, :val1, and :val2), and printing the data in a tabular format. It pads shorter arrays with empty strings to align the output and prints the id only on the first line for each entry. The code effectively processes the data array and presents it in a readable, aligned format, handling cases where the val1 and val2 arrays have different lengths.

Ruby code snippet

data = [
  {:id => "a", :val1 => [1, 2, 3], :val2 => [3, 4]},
  {:id => "b", :val1 => [0], :val2 => [9, 8, 7]}
]
#=> 
[{id: "a", val1: [1, 2, 3], val2: [3, 4]},


puts data.first.keys.join("\t")
id	val1	val2
#=> nil

data.each do |entry|
  id = entry[:id]
  val1 = entry[:val1]
  val2 = entry[:val2]
  
  max_length = [val1.length, val2.length].max
  max_length.times do |i|
      id_output = (i == 0 ? id : "")
      
      val1_output = (val1[i].nil? ? "" : val1[i])
      val2_output = (val2[i].nil? ? "" : val2[i])
      
      puts [id_output, val1_output, val2_output].join("\t")
  end
end
a	1	3
	2	4
	3	
b	0	9
		8
		7
#=> 
[{id: "a", val1: [1, 2, 3], val2: [3, 4]},
 {id: "b", val1: [0], val2: [9, 8, 7]}]

Executed with Ruby 3.4.5.