0

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 want to 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"
      },
 }
]
3
  • What are x1, x2, x3? they seem like variables. Do you want their names in output hash? That seems impossible to do. May be you need to look at your problem differently Commented Jun 4, 2016 at 16:33
  • "I forget to surround them by quotes", then edit your question and fix them please. It's important that your examples and code be accurate. Please read "minimal reproducible example". Commented Jun 4, 2016 at 20:40
  • What is the purpose of "2" and "3" in c? Are then insignificant/ignored? If they're significant then how are you expecting them to be used? Your selected answer doesn't match your desired output at this point. Commented Jun 4, 2016 at 20:42

1 Answer 1

4
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}}" 

(I broke the JSON string to two lines to avoid the need for horizontal scrolling.)

Alternatively,

pairs = [d.map { |a| a.map(&:to_sym) }, e].transpose.map(&:transpose)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.