How to quickly print Ruby hashes in table format?

Is there a way to quickly print a ruby ​​hash in table format to file? For instance:

keyA   keyB   keyC   ...
123    234    345
125           347
4456
...

where the hash values ​​are arrays of different sizes. Or uses a double loop the only way?

thank

+5
source share
4 answers

Here's the steenslag version that works when arrays don't have the same size:

size = h.values.max_by { |a| a.length }.length
m    = h.values.map { |a| a += [nil] * (size - a.length) }.transpose.insert(0, h.keys)

nil seems like a reasonable placeholder for missing values, but of course you can use anything that makes sense.

For instance:

>> h = {:a => [1, 2, 3], :b => [4, 5, 6, 7, 8], :c => [9]}
>> size = h.values.max_by { |a| a.length }.length
>> m = h.values.map { |a| a += [nil] * (size - a.length) }.transpose.insert(0, h.keys)
=> [[:a, :b, :c], [1, 4, 9], [2, 5, nil], [3, 6, nil], [nil, 7, nil], [nil, 8, nil]]
>> m.each { |r| puts r.map { |x| x.nil?? '' : x }.inspect }
[:a, :b, :c]
[ 1,  4,  9]
[ 2,  5, ""]
[ 3,  6, ""]
["",  7, ""]
["",  8, ""]
+4
source

Try this stone that I wrote (prints hashes, ruby ​​objects, ActiveRecord objects in tables): http://github.com/arches/table_print

+3
h = {:a => [1, 2, 3], :b => [4, 5, 6], :c => [7, 8, 9]}
p h.values.transpose.insert(0, h.keys)
# [[:a, :b, :c], [1, 4, 7], [2, 5, 8], [3, 6, 9]]
+2

, . , , :

data = { :keyA => [123, 125, 4456], :keyB => [234000], :keyC => [345, 347] }

length = data.values.max_by{ |v| v.length }.length

widths = {}
data.keys.each do |key|
  widths[key] = 5   # minimum column width

  # longest string len of values
  val_len = data[key].max_by{ |v| v.to_s.length }.to_s.length
  widths[key] = (val_len > widths[key]) ? val_len : widths[key]

  # length of key
  widths[key] = (key.to_s.length > widths[key]) ? key.to_s.length : widths[key]
end

result = ""
data.keys.each {|key| result += key.to_s.ljust(widths[key]) + " " }
result += "\n"

for i in 0.upto(length)
  data.keys.each { |key| result += data[key][i].to_s.ljust(widths[key]) + " " }
  result += "\n"
end

# TODO write result to file...

.

+1

All Articles