0

I'm trying to make a nested (and thus sorted) array of hashes like so:

[{ stack: 'stack name', id: 1,
    boxes: [{
      box: 'whatever box',
      id: 1,
      vars: [{
        var: 'some name',
        id: 22,
      }, 
      { var: 'another name',
        id: 4 
      }]
    }, {
      box: 'another box',
      id: 99,
      vars: [{
        var: 'another',
        id: 999
      }]
    }    
  }]
}]

The method I've come up with so far is this which doesn't work but I'm totally stack as to how to nest these objects to maintain their hierarchy (a Stack can have many Boxes, a Box can have many TemplateVariables.

master = []
@template.stacks.alphabetised.each_with_index do |stack, i|
  master << { stack: stack.name, id: stack.id }
  stack.boxes.indexed.each_with_index do |box, j|
    master[i] = { box: box.name, id: box.id }
    box.template_variables.indexed.each do |var|
      master[i][j] = { var: var.name, id: var.id }
    end
  end
end
master

This seems to return nothing despite those objects definitely being there (and I know my structure is off, too). Am I doing something wrong?

1
  • The syntax isn't correct for the first one. Commented Jan 26, 2017 at 14:58

1 Answer 1

1

You could use nested maps :

################################################
# Initialization code. Different from yours.
def stacks
  Array.new(2){|i| "Stack #{i+1}"}
end

@box_id = 0
def boxes
  Array.new(2){ "Box #{@box_id += 1}"}
end

@var_id = 0
def vars
  Array.new(2){ "Var #{@var_id += 1}"}
end
################################################

stack_data = stacks.map.with_index do |stack,i|
  box_data = boxes.map.with_index do |box,j|
    var_data = vars.map.with_index do |var,k|
      {var: var, id: k}
    end
    {box: box, id: j, vars: var_data}
  end
  {stack: stack, id: i, boxes: box_data}
end

require 'pp'
pp stack_data

It outputs :

[{:stack=>"Stack 1",
  :id=>0,
  :boxes=>
   [{:box=>"Box 1",
     :id=>0,
     :vars=>[{:var=>"Var 1", :id=>0}, {:var=>"Var 2", :id=>1}]},
    {:box=>"Box 2",
     :id=>1,
     :vars=>[{:var=>"Var 3", :id=>0}, {:var=>"Var 4", :id=>1}]}]},
 {:stack=>"Stack 2",
  :id=>1,
  :boxes=>
   [{:box=>"Box 3",
     :id=>0,
     :vars=>[{:var=>"Var 5", :id=>0}, {:var=>"Var 6", :id=>1}]},
    {:box=>"Box 4",
     :id=>1,
     :vars=>[{:var=>"Var 7", :id=>0}, {:var=>"Var 8", :id=>1}]}]}]
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.