Moamen Naanou Moamen Naanou - 6 months ago 29
Ruby Question

Ruby Combine three arrays into single json object

I have three arrays:

c = ["1", "2", "3"]
d = [[x1,x2,x3],[x4,x5,x6], [x7,x8,x9]]
e = [[20,21,22], [23,24,25], [26,27,28]]


And I wanna merge them together in Ruby to get this json result:

[
{"1":{
"x1":"20",
"x2":"21",
"x3":"22"
},
{
"x4":"23",
"x5":"24",
"x6":"25"
},
{
"x7":"26",
"x8":"27",
"x9":"28"
},
}
]



  • Your cooperation will be highly appreciated :)


Answer
c = ["1", "2", "3"]
d = [['x1','x2','x3'],['x4','x5','x6'], ['x7','x8','x9']]
e = [[20,21,22], [23,24,25], [26,27,28]]

require 'json'

pairs = d.map { |a| a.map(&:to_sym) }.zip(e).map(&:transpose)
  #=> [[[:x1, 20], [:x2, 21], [:x3, 22]],
  #    [[:x4, 23], [:x5, 24], [:x6, 25]],
  #    [[:x7, 26], [:x8, 27], [:x9, 28]]]    
c.each_with_object({}) { |s,h| h[s] = pairs.shift.to_h }.to_json
  #=> "{\"1\":{\"x1\":20,\"x2\":21,\"x3\":22},\"2\":{\"x4\":23,\"x5\":24,\"x6\":25},\"3\":{\"x7\":26,\"x8\":27,\"x9\":28}}" 
Comments