Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@wteuber
Last active July 3, 2016 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wteuber/af291a4246bd527a58ca5b500b62bf8d to your computer and use it in GitHub Desktop.
Save wteuber/af291a4246bd527a58ca5b500b62bf8d to your computer and use it in GitHub Desktop.
table = [
{a: 'asd', b: 'asd/asd/sdf/hk/lklkjlkj.lol', c: 'Lorem foo bar baz lol :-)'},
{a: 'aassddaassdd', b: 'asd/lll.lol', c: 'Lorem foo bar baz lol2 :-)'},
{a: 'a', b: 'test/[:id].format', c: ';-)'}]
max_length = -> (k) { [k, table.map { |e| e[k]}.max_by(&:length).length + 3]}
widths = Hash[%i(a b c).map(&max_length)]
# => {:a=>15, :b=>30, :c=>29}
puts table.map{|route| route.map{|key, val| val.ljust(widths[key])}.join}
# asd asd/asd/sdf/hk/lklkjlkj.lol Lorem foo bar baz lol :-)
# aassddaassdd asd/lll.lol Lorem foo bar baz lol2 :-)
# b test/[:id].format :-(
array_of_objects = [{abc:1,a:2,b:3,c:4}, {'ddddddddd' => 1212121212121212}, {[123,123,123,123] => 's'}]
props = %i(keys to_s length)
filter = -> (obj) { props.map { |prop| obj.send(prop).to_s } }
table = array_of_objects.map(&filter)
max = -> (column) { column.max_by(&:size).size + 6 }
lengths = table.transpose.map(&max)
ljust = -> (str, idx) { str.ljust(lengths[idx]) }
format = -> (row) { row.each_with_index.map(&ljust).join }
puts table.map(&format)
# [:abc, :a, :b, :c] {:abc=>1, :a=>2, :b=>3, :c=>4} 4
# ["ddddddddd"] {"ddddddddd"=>1212121212121212} 1
# [[123, 123, 123, 123]] {[123, 123, 123, 123]=>"s"} 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment