Quickly printing data in columns on your Ruby console

Posted . Visible to the public.

Dump this method into your Ruby console to quickly print data in columns. This is helpful for e.g. comparing attributes of a set of Rails records.

def tp(objects, *method_names)
  terminal_width = `tput cols`.to_i
  cols = objects.count + 1 # Label column
  col_width = (terminal_width / cols) - 1 # Column spacing

  Array(method_names).map do |method_name|
    cells = objects.map{ |o| o.send(method_name).inspect }
    cells.unshift(method_name)

    puts cells.map{ |cell| cell.to_s.ljust(col_width) }.join ' '
  end

  nil
end

Usage examples:

tp Video.where(key: '123'), :created_at, :updated_at, :published
tp [album1, album2], :title, :image_count
Profile picture of Dominik Schöler
Dominik Schöler
Last edit
Dominik Schöler
Keywords
table
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2017-05-24 12:20)