-4

How can I convert array of arrays (CSV-liks with headers) to an array of hashes ?

headers = [['foo', 'bar', 'baz']]
data = [[1,2,3], [4,5,6], [7,8,9]...]
arr_of_arrs = headers + data

arr_of_arrs_to_structured_hash

expected output be like

[
 {foo: 1, bar: 2, baz: 3}
 {foo: 4, bar: 5, baz: 6}
 {foo: 7, bar: 8, baz: 9}
]

EDIT : sorry I just realized my output wasn't clear. Basically the data ara array of rows just like in CSV (except my data isn't coming from a CSV)

Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164
  • 4
    Please read "[ask]" and "[mcve]". Show us your code attempt. Currently it looks like you kind-of started then bailed and want us to write it for you, which is off-topic as SO isn't a code writing service. "[How much research effort is expected of Stack Overflow users?](http://meta.stackoverflow.com/questions/261592)" is important. A hint toward solving the problem is that `map`, `zip` and `to_h` are your friends. – the Tin Man May 18 '17 at 23:03
  • 1
    The logic is not clear. How is the input related to the expected output? – sawa May 19 '17 at 00:55
  • Did you start with an actual CSV file? Then you probably want to consider using the CSV gem, it will save you the hassle of creating your arrays of arrays. – Mark Thomas May 19 '17 at 01:38
  • @theTinMan Sorry about that just realized indeed my example wasn't clear (and there was a typo on the last value). I have actually looked at a lot of CSV-related posts and blog enties, but they all mention how to go read/parse CSV but not really how to convert such an array of arrays to hash/JSON (or I'd have to write to a CSV file first =_=) – Cyril Duchon-Doris May 19 '17 at 07:29

1 Answers1

1
headers = [['foo', 'bar', 'baz']]
data = [[1,2,3], [2,3,4]]

data.map(&headers.first.method(:zip)).map(&:to_h)
#⇒ [
#  [0] {
#    "foo" => 1
#    "bar" => 2,
#    "baz" => 3,
#  },
#  [1] {
#    "foo" => 2
#    "bar" => 3,
#    "baz" => 4,
#  }
# ]
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160