Skip to content

Instantly share code, notes, and snippets.

@slawosz
Created July 30, 2013 19:01
Show Gist options
  • Save slawosz/6115816 to your computer and use it in GitHub Desktop.
Save slawosz/6115816 to your computer and use it in GitHub Desktop.
array = [['Number', 'Name'], [1, 'Foo'], [2, 'Bar'], [3, 'Baz']]
pretty_table(array)
# printed result:
+--------+--------+
| Number | Name |
+--------+--------+
| 1 | Foo |
+--------+--------+
| 2 | Bar |
+--------+--------+
| 3 | Baz |
+--------+--------+
@baisa
Copy link

baisa commented Aug 19, 2013

array = [['Number', 'Name'], [1, 'Foo'], [2, 'Bar'], [3, 'Baz']]

def pretty_table(array)

new_array = array.collect {|elem| 
    elem.collect! {|el| el.to_s}
    elem.max_by {|el| el.length}
}
m = new_array.max_by {|elem| elem.length}

i = 0
z = "|" + "#{array[i][0]}".ljust(m.size) + " | " + "#{array[i][1]}".ljust(m.size) +  " | "
w = z.length


puts w

string = ""
array.each do |elem|
    string << "-" * w
    string << "\n"
    string << "|" + "#{array[i][0]}".ljust(m.size) + " | " + "#{array[i][1]}".ljust(m.size) +  " | "
    string << "\n"



    i = i + 1

end


string << "-" * w

end

print pretty_table(array)

@baisa
Copy link

baisa commented Aug 19, 2013

|Number|
|Name  |

|1     |
|Foo   |

|2     |
|Bar   |

|3     |
|Baz   |


or

-------
|Number|-------
|Name  |-------
|1     |-------
|Foo   |-------
|2     |-------
|Bar   |-------
|3     |-------

or

-------
|Number|-------
|Name  |
-------
|1     |-------
|Foo   |
-------
|2     |-------
|Bar   |
-------
|3     |-------
|Baz   |

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment