Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print an array into a table in Ruby

Tags:

ruby

I have an array and my goal is to print the code in a way so it outputs the following:

Output Table

How can i do that?

like image 440
Nuno Gomes Avatar asked Nov 29 '22 07:11

Nuno Gomes


1 Answers

I imagine there are lots of gems available for doing this, but if you want to roll-your-own, you could do it like this, in a fairly general way:

Your input is comprised of column labels:

col_labels = { date: "Date", from: "From", subject: "Subject" }

and the data for the rows:

arr = [{date: "2014-12-01", from: "Ferdous", subject: "Homework this week"},
       {date: "2014-12-01", from: "Dajana", subject: "Keep on coding! :)"},
       {date: "2014-12-02", from: "Ariane", subject: "Re: Homework this week"}]

where col_labels and the elements of arr have the same keys.

From this point on, the code is general. First construct a hash @columns (which I've made an instance variable for convenience).

@columns = col_labels.each_with_object({}) { |(col,label),h|
  h[col] = { label: label,
             width: [arr.map { |g| g[col].size }.max, label.size].max } }
  # => {:date=>    {:label=>"Date",    :width=>10},
  #     :from=>    {:label=>"From",    :width=>7},
  #     :subject=> {:label=>"Subject", :width=>22}}

def write_header
  puts "| #{ @columns.map { |_,g| g[:label].ljust(g[:width]) }.join(' | ') } |"
end

def write_divider
  puts "+-#{ @columns.map { |_,g| "-"*g[:width] }.join("-+-") }-+"
end

def write_line(h)
  str = h.keys.map { |k| h[k].ljust(@columns[k][:width]) }.join(" | ")
  puts "| #{str} |"
end

write_divider
write_header
write_divider
arr.each { |h| write_line(h) }
write_divider

+------------+---------+------------------------+
| Date       | From    | Subject                |
+------------+---------+------------------------+
| 2014-12-01 | Ferdous | Homework this week     |
| 2014-12-01 | Dajana  | Keep on coding! :)     |
| 2014-12-02 | Ariane  | Re: Homework this week |
+------------+---------+------------------------+

If you want to reverse the display and make it a bit larger, like yours, first execute:

$_!.reverse
$_@ += 4

Output Table

like image 163
Cary Swoveland Avatar answered Dec 22 '22 22:12

Cary Swoveland