Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create table directly from Hash #19

Open
vaibhavatul47 opened this issue Apr 5, 2018 · 4 comments
Open

Create table directly from Hash #19

vaibhavatul47 opened this issue Apr 5, 2018 · 4 comments

Comments

@vaibhavatul47
Copy link

vaibhavatul47 commented Apr 5, 2018

It would be great to add support for data saved in array of hash. Eg:

users = [
  { name: "Foo", city: "XYZ", admin: true },
  { name: "Bar", zip: 987654, city: "ABC"}
]

table = TTY::Table.new(users)
renderer = TTY::Table::Renderer::Unicode.new(table)
renderer.render

Output:

#  ┌─────┬───────┬─────┬─────┐
#  │name │zip    │city │admin│
#  ├─────┼───────┼─────┼─────┤
#  │Foo  │       │XYZ  │✔    │
#  │Bar  │987654 │ABC  │     │
#  └─────┴───────┴─────┴─────┘

Current implementation expects each header to have value defined for each row. If values are not available then it is to be replaced by nil. For above example sample input would be:

users = [ {
  name:  ["Foo", "Bar"],
  zip:   [nil, 987654],
  city:  ["XYZ", "ABC"],
  admin: [true, nil]
} ]

I can submit a PR if required.

@slowbro
Copy link
Contributor

slowbro commented Oct 7, 2019

Hi @vaibhavatul47; if you have a patch for this completed already, let me know - otherwise I may tackle this.

@vaibhavatul47
Copy link
Author

I had it somewhere on my machine, I'll share the patch shortly.

@dishcandanty
Copy link

I know this is old, but @vaibhavatul47 this would be super nice to have :)

@MadBomber
Copy link

No change to the library is required. It has established its contract w/r/t its API. Just convert your data to match the contract like this:

#!/usr/bin/env ruby
# convert_hash_to_data.rb

require 'tty-table'

headers = [:key1, :key2, :key3]

array_of_hashes = [
  {
    key1: 'one',
    key2: 'two'
  },
  {
    key1: 'one',
    key2: 'two',
    key3: 'three'
  },
  {
    key2: 'two',
    key3: 'three'
  },
  {
    key3: 'three'
  }
]

def convert_hash_to_data(headers, array_of_hashes)
  data = []
  array_of_hashes.each do |entry|
    row = []
    headers.each do |key|
      row << entry[key]
    end
    data << row
  end

  data
end

data = convert_hash_to_data(headers, array_of_hashes)

table = TTY::Table.new(headers, data)
puts table

__END__

produces this output ...

key1 key2 key3
one  two
one  two  three
     two  three
          three

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

No branches or pull requests

5 participants