Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quickly print Ruby hashes in a table format?

Tags:

arrays

ruby

hash

Is there a way to quickly print a ruby hash in a table format into a file? Such as:

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

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

Thanks

like image 971
zanbri Avatar asked Oct 26 '11 14:10

zanbri


3 Answers

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

like image 122
Chris Doyle Avatar answered Sep 26 '22 23:09

Chris Doyle


Here's a version of steenslag's that works when the arrays aren't 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 you can, of course, use whatever makes sense.

For example:

>> 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, ""]
like image 33
mu is too short Avatar answered Sep 23 '22 23:09

mu is too short


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]]
like image 36
steenslag Avatar answered Sep 22 '22 23:09

steenslag